Problem 5
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
Solution in C#
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var n = 20; for (var i = 19; i >= 2; i--) { if (n % i != 0) { n += 20; i = 20; } } Console.WriteLine(n); Console.ReadKey(); } } }
Solution in Perl
sub problem5 {
my $n = 20;
for ( my $i = 19 ; $i >= 2 ; $i-- ) {
if ( $n % $i != 0 ) { $n += 20; $i = 20; }
}
print $n;
}
problem5();
Python
def problem5():
n = 20
i = 19
while (i >= 2):
if n % i != 0: n += 20; i = 20
i -= 1
print n
Go
func problem5() {
n := 20
for i := 19; i >= 2; i-- {
if n%i != 0 {
n += 20
i = 20
}
}
fmt.Println(n)
}
func main() {
problem5()
}
C++
void problem5() {
long long n = 20;
for (int i = 19; i >= 2; i--) {
if (n % i != 0) { n += 20; i = 20; }
}
cout << n << endl;
}
Bash (very slow)
function problem5 {
local n=20
local i=19
while ((i >= 2)); do
if ((n % i != 0)); then ((n += 20)); ((i=20)); fi
((i--))
done
echo $n
}
problem5
Javascript
function gcd(a,b) {return b==0?a:gcd(b,a%b)}
function lcm(a,b) {return a*b/gcd(a,b)}
var r=1;
for(var i=2; i<=20; i++) r=lcm(r,i);
r
Racket
(define (problem5)
(display (apply lcm (range 1 21))))
(problem5)
Haskell
main = print $ foldr1 lcm [1..20]
* Clojure
(defn gcd2 [a b]
(cond (zero? b) a
:else (recur b (rem a b))))
(defn lcm2 [a b]
(/ (* a b) (gcd2 a b)))
(defn problem5 []
(println (reduce lcm2 (range 1 21))))
* newLISP
(define (lcm a b) (/ (* a b) (gcd a b)))
(apply lcm (sequence 1 20) 2)
Common Lisp
(let ((r 1))
(loop for i from 2 to 20 do
(setq r (lcm r i)))
(print r))
'Project Euler' 카테고리의 다른 글
Project Euler Problem 7 (0) | 2012.05.28 |
---|---|
Project Euler Problem 6 (0) | 2012.05.28 |
Project Euler Problem 4 (0) | 2012.05.28 |
Project Euler Problem 211 (0) | 2012.05.28 |
Project Euler Problem 58 (0) | 2012.05.28 |