#The sum of the squares of the first ten natural numbers is,
#12 + 22 + ... + 102 = 385
#The square of the sum of the first ten natural numbers is,
#(1 + 2 + ... + 10)2 = 552 = 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.
#
#shao@shao-desktop:~/桌面$ ruby 12.rb
#338350
#25502500
#差值:25164150
def natural_number_sum
sum_of_squares = 0
squares_of_sum = 0
sum = 0
1.upto(100) do |i|
sum_of_squares += i**2
sum += i
end
squares_of_sum = sum**2
puts sum_of_squares
puts squares_of_sum
puts squares_of_sum - sum_of_squares
end
natural_number_sum
ProjectRuler-6
最新推荐文章于 2024-07-12 10:50:00 发布