Solved ProjectEuler/021: php, ruby, c

This commit is contained in:
FuryFire 2012-03-12 10:18:06 +01:00
parent 36c31696a9
commit 5dc80b4e9f
4 changed files with 94 additions and 0 deletions

23
ProjectEuler/021/desc.yml Normal file

@ -0,0 +1,23 @@
title: Evaluate the sum of all amicable pairs under 10000.
url: http://projecteuler.net/problem=21
desc: |
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.
solution: Bruteforce
todo: Implement caching in other solutions
solutions:
solve.php:
desc: (Uses a cache to find allready calculated values for d()
language: php
solve.rb:
desc: Basic solution
language: ruby
solve.c:
desc: ANSI C solution (Compiled with TCC)
language: c

28
ProjectEuler/021/solve.c Normal file

@ -0,0 +1,28 @@
#define MAX 10000
#include <stdio.h>
#include <math.h>
int d( int input) {
int sum = 0;
int n;
for(n=1;n<input;n++) {
if(input % n == 0)
sum += n;
}
return sum;
}
int main( )
{
int result = 0;
int number;
int d_sum;
for(number = 1; number < MAX; number++) {
d_sum = d(number);
if(number != d_sum && number == d(d_sum)) {
result += number;
}
}
printf("%d", result);
}

@ -0,0 +1,23 @@
<?php
define('MAX',10000);
function d($int) {
static $cache;
if(isset($cache[$int])) {return $cache[$int]; }
$sum = 0;
for($n=1;$n<$int;$n++) {
if($int % $n == 0)
$sum += $n;
}
$cache[$int] = $sum;
return $sum;
}
$result = 0;
for($number = 1; $number < MAX; $number++) {
$d_sum = d($number);
if($number != $d_sum AND $number == d($d_sum)) {
$result += $number;
}
}
echo $result;

20
ProjectEuler/021/solve.rb Normal file

@ -0,0 +1,20 @@
MAX = 10000
def d(num)
sum = 0
1.upto(num-1) do |d|
if(num % d == 0)
sum += d
end
end
return sum
end
result = 0
Range.new(0,MAX,true).each do |number|
d_sum = d(number)
if(number != d_sum && number == d(d_sum))
result += number
end
end
puts result