Skip to content

Instantly share code, notes, and snippets.

@kopiro
Created September 8, 2011 07:42
Show Gist options
  • Save kopiro/1202863 to your computer and use it in GitHub Desktop.
Save kopiro/1202863 to your computer and use it in GitHub Desktop.
Find amicable numbers in C
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
long sumod(long x) {
long i, s = 1;
for (i=2; i<=(x/2); i++)
if ((int)x%i==0)
s += i;
return s;
}
int main() {
const long L = LONG_MAX;
// Warning, if the program crashes, use a minor value of L (like 9999999) :
//const long L = 9999999;
long* cache = malloc(L*sizeof(long));
long* jvalues = malloc(L*sizeof(long));
if (cache==NULL || jvalues==NULL) {
printf("\nError while initializing memory.\n");
exit(-1);
}
long x;
for (x=0; x<L; x++) {
cache[x] = 0;
jvalues[x] = 0;
}
for (x=1; x<L; x++) {
if (!cache[x]) cache[x] = sumod(x);
if (!cache[cache[x]]) cache[cache[x]] = sumod(cache[x]);
if (cache[cache[x]]==x && jvalues[x]==0) {
jvalues[x] = cache[x];
jvalues[cache[x]] = x;
printf("%ld, %ld\n", x, cache[x]);
fflush(stdout);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment