Esercizio 21

Stato
Discussione chiusa ad ulteriori risposte.

Cynical

Utente Silver
10 Febbraio 2011
2
1
0
51
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

Ecco la mia soluzione

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

int d(int x); // funzione che restituisce la sommatoria dei divisori di x

int main(void)
{ int a,b,sum;
 
  sum = 0;
  for(a=1;a<10000;a++)
     if(a != (b = d(a)) && (d(b) == a))
         sum += a;

  printf("la somma è : %d\n",sum);
 
  return 0;
  
}

int d(int x)
{ int i,half,sum;
  
  sum=1;
  half = (int) sqrt(x) +1; // parte intera della metà di x..
  for(i=2;i<=half;i++)
      if(!(x%i)) 
         sum +=(i + x/i);

  return sum;
}

Codice:
cynical-kris@cynical-kris-laptop:~/Desktop/Programmi/progettoEulero/problem21$ time ./a.out
la somma è : 31626

real	0m0.031s
user	0m0.024s
sys	0m0.004s
 
Stato
Discussione chiusa ad ulteriori risposte.