« Project Euler ( Problem 29 ) | Main | 今週の戯れ歌 »

Project Euler ( Problem 5, 6, 16 )

大変有害なものを晒している気もするが、お許しあれ。

●Problem 5
foldl lcm 1 [1..10]
2520

foldl lcm 1 [1..20]
232792560

●Problem 6
(x + y)^2 = x^2 + 2xy + y^2

(x + y)^2 - x^2 - y^2 = 2xy

(x + y + z)^2 - x^2 - y^2 - z^2 = 2xy + 2xz + 2yz

import Data.List
Prelude Data.List> sort [x*y | x<-[1..10], y<-[1..10], x /= y ]
[2,2,3,3,4,4,5,5,6,6,6,6,7,7,8,8,8,8,9,9,10,10,10,10,12,12,12,12,14,14,15,15,16,16,18,18,18,18,20,20,20,20,21,21,24,24,24,24,27,27,28,28,30,30,30,30,32,32,35,35,36,36,40,40,40,40,42,42,45,45,48,48,50,50,54,54,56,56,60,60,63,63,70,70,72,72,80,80,90,90]

sum [ x*y | x<-[1..10], y<-[1..10], x /= y ]
2640

sum [ x*y | x<-[1..100], y<-[1..100], x /= y ]
25164150

別解
(sum [1..10] )^2 - sum [ x^2 | x<-[1..10] ]
2640
(sum [1..100] )^2 - sum [ x^2 | x<-[1..100] ]
25164150

計算速度が問題になるほどのものではなかった。
別解であっても十分速い。

●Problem 16
#!/usr/bin/ruby
(1..1000).each{ |n|
p = 2 ** n
sum = 0
p.to_s.split(//).each{|i| sum= sum + i.to_i }
print "2^#{n} = #{p} -> #{sum}\n"
}
__END__

2^1 = 2 -> 2
2^2 = 4 -> 4
2^3 = 8 -> 8
2^4 = 16 -> 7
2^5 = 32 -> 5
2^6 = 64 -> 10
2^7 = 128 -> 11
2^8 = 256 -> 13
2^9 = 512 -> 8
2^10 = 1024 -> 7
...
2^1000 =
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
-> 1366

これほどの長整数がきちんと計算されているかは不明だが、
途中経過を見て、いちおう「らしい」事は確認した。
(これをもって正しいというには相当の勇気が必要)。


2^1000=1.0715E+301 なのはエクセルでも確認できた。
VBAで計算させようとしたが、持っている数値は頭の
15桁だけであり、計算できなかった(トホホ)。

1071508607186270000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

|

« Project Euler ( Problem 29 ) | Main | 今週の戯れ歌 »

Comments

Post a comment



(Not displayed with comment.)


Comments are moderated, and will not appear on this weblog until the author has approved them.



TrackBack


Listed below are links to weblogs that reference Project Euler ( Problem 5, 6, 16 ):

« Project Euler ( Problem 29 ) | Main | 今週の戯れ歌 »