Solved ProjectEuler/021: php, ruby, c
This commit is contained in:
23
ProjectEuler/021/desc.yml
Normal file
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
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);
|
||||
}
|
23
ProjectEuler/021/solve.php
Normal file
23
ProjectEuler/021/solve.php
Normal file
@ -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
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
|
Reference in New Issue
Block a user