problem 30

Stato
Discussione chiusa ad ulteriori risposte.

cyd

Utente Silver
11 Giugno 2007
59
0
1
70
l'esercizio consiste nel risolvere il problema 30 ma generalizzando la soluzione per N qualunque , dove N e' l'esponente di riferimento (nell'esempio N=4 e nel problema N=5)
Codice:
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4

As 1 = 1^4 is not a sum it is not included.

The sum of these numbers is 1634 + 8208 + 9474 = 19316.

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

la soluzione per ora deve soddisfare N=4 e N=5 poi al massimo si confrontano altri valori.

Codice:
#include <stdio.h>
#include <math.h>

#define N 5

unsigned int intlen(unsigned int a){
	register int i=10;
	int l=1;
	for(;i<a;i*=10) l++;
	return l;
}

int pow_sum(unsigned int n,unsigned int len){
	register int j=0,b=n,ps=0;
	for(;j<len;j++,b=(int)b/10) ps+=pow(b%10,N);
	return ps;
}


int main(void){

	unsigned int cnt,c,len=0,sum=0;

	c=pow(9,N);
	for(cnt=c;intlen(cnt)>len;cnt+=c) len++;

	for(;cnt>0;cnt--)
		sum+=cnt*(cnt==pow_sum(cnt,len));

	printf("sum: %d",sum-1*(sum!=0));

	return 0;
}
 
Stato
Discussione chiusa ad ulteriori risposte.