Project Euler

Problem #23

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

Erlang: Running time = 18.0s
+%run_procs

+%pow

+%cartesian_product

+%echo

+%prime_list

+%prime_iterator

+%factor

+%product

+%divisors

p23()->
	Abunds=lists:filter(fun(X)->lists:sum(divisors(X))>2*X end,lists:seq(12,28123)),
	AbundSet=sets:from_list(Abunds),
	Ans=run_procs(28123,fun(N)->[euler,p23,[N,Abunds,AbundSet,self()]] end,
		fun
			(A,false)->A;
			(A,B)->A+B end,0),
	io:format("~w~n",[Ans]).

p23(N,[NextAb|_],_,Parent) when NextAb >= N -> Parent ! N;
p23(N,[NextAb|Abs],Abset,Parent)->
	case sets:is_element(N-NextAb,Abset) of
		true->
			Parent ! false;
		false->
			p23(N,Abs,Abset,Parent)
	end.

Ruby: Running time = 9.45s
+#cartesian_product

+#PrimeList

+#Enumerable

$p23abs=[]

def p23abs_from(fax,prod,prime_i)
  while((mult=(prod*(n=PrimeList.get(prime_i))))<28123)
    p23abs_from(fax+[n],mult,prime_i)
    prime_i+=1
  end
  return if fax.length==0
  distinct_primes={}
  while fax.length >0
    n=fax.pop
    i=1
    while(fax.length>0 and fax.last==n)
      i+=1
      fax.pop
    end
    distinct_primes[n]=i
  end
  product_of=[]
  distinct_primes.keys.each do |k|
    t=[1]
    i=distinct_primes[k]
    i.times{t.push(t.last*k)}
    product_of.push t
  end
  $p23abs.push(prod) if cartesian_product(*product_of).map{|j|j.product}.sum>2*prod
end

def p23
  p23abs_from([],1,0)
  testing=[]
  absTest=$p23abs.to_set
  $p23abs.sort!{|u,v|v<=>u}
  nosums=(1..28123).reject do |i|
    testing.push($p23abs.pop) if $p23abs.last <= i/2
    testing.any?{|j|absTest.include?(i-j)}
  end  
  puts nosums.sum
end