Problem 6
The sum of the squares of the first ten natural numbers is,
1^(2) + 2^(2) + … + 10^(2) = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)^(2) = 55^(2) = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
Działa od >= 1.8.7:
puts (1..100).inject(:+) ** 2 - (1..100).map {|e| e ** 2 }.inject(:+)
Dla <= 1.8.6:
puts (1..100).inject(0) {|s, e| s + e} ** 2 - (1..100).map {|e| e ** 2 }.inject(0) {|s, e| s + e}
teamon
3
A moze:
puts (1..100).inject{|s,e| s+=e} ** 2 - (1..100).inject{|s,e| s+=e**2}
=> 25164150
:>
timmy
4
jak ktoś nie ma Ruby 1.9
p (1..100).inject {|sum,x| sum + x} ** 2 - (1..100).map {|y| y ** 2}.inject {|sum,z| sum + z}
25164150
Kokos
5
x = y = 0
1.upto(100) {|i| x += i; y += i * i}
p x * x - y