Amicable number calculator
Golfscript (51 50 chars)
2{.{:a,(\{.a\%!*+}/}:^~1$>{..^^={[..^](\p}*}*).}do
The core is the override of ^
as :a,(\{.a\%!*+}/
which finds the aliquot of the number on the top of the stack (call it n
) by the grossly inefficient approach of considering every number from 1
to n-1
to see whether it's a factor.
C (gcc), 162, 158, 146, 138 chars
s(n){int x=1,i=2;for(;i<=sqrt(n);++i)if(n%i==0)x+=i+n/i;return x;}main(i,a){for(;;)a=s(i),((a>i)?s(a):0)==i++?printf("%d,%d\n",i-1,a):0;}
compile with gcc using gcc amic.c -o amic -lm -include math.h
To shorten it any further I suspect the algorithm would have to change.
Edits:
162->158: Consolidated the variable b
into the printf conditional.
158->146: Utilized main to declare a
instead of using a global var, also using implicit int
of the parameter and return type for the function s(n)
146->138: Add Lowjacker's suggestion of removing the cast to double. Thanks!
Scala (120 chars):
def d(n:Int)=(1 to n-1).filter(n%_==0)
def i(x:Int,y:Int)=x!=y&&d(y).sum==x
(1 to Int.MaxValue).filter(x=>i(x,d(x).sum))