summaryrefslogtreecommitdiff
path: root/euler21.c
blob: d18e55602cfd682745e5dbd46d930fae564ee9b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <stdio.h>
#include <math.h>
#define MAX 9999

int firstdiv(int n)
{
	int i;
	int q=ceil(sqrt(n));
	for (i=2;i<=q;++i){
		if (n%i==0)
			return i;
	}
	return n;
}

int divexp(int n,int d)
{
	int dd=1;
	while (n%d==0){
		n/=d;
		dd*=d;
	}
	return dd;
}

int sumdiv(int n)
{
	if (n==1)
		return 1;

	int fd=firstdiv(n);
	int fdexp=divexp(n,fd);
	return sumdiv(n/fdexp)*(fdexp*fd-1)/(fd-1);
}

int main()
{
	int d[MAX+1],i,sum=0;
	for (i=1;i<=MAX;++i){
		d[i]=sumdiv(i)-i;
	}
	for (i=1;i<=MAX;++i){
		if (i<d[i] && d[i]<=MAX && i==d[d[i]]){
			sum+=i+d[i];
		}else if (d[i]>MAX && sumdiv(d[i])-d[i]==i){
			sum+=i;
		}
	}
	printf("%d\n",sum);
	return 0;
}