Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Problem
- #Write a method that computes the difference between the square of the sum of the first n positive integers and the sum of the squares of the first n positive integers.
- #(3) == 22
- # -> (1 + 2 + 3)**2 - (1**2 + 2**2 + 3**2)
- # (n + n + n)**2 - (n**2 + n**2 + n**2)
- #Examples:
- #sum_square_difference(3) == 22
- # -> (1 + 2 + 3)**2 - (1**2 + 2**2 + 3**2)
- #sum_square_difference(10) == 2640
- #sum_square_difference(1) == 0
- #sum_square_difference(100) == 25164150
- #Data Types:
- #Input: an integer.
- #Output: an integer. sum of squares minus squares of sums
- #Structure: to_s.chars, map method, each, **upto method** or **times method**
- #Algorithm/Logic:
- #sq_sum = 0
- #sum_square = 0
- #1.upto(integer) do |num|
- #sq_sum += num ##square sq_num later##
- #sum_squares += num**2
- #retrun sq_sum ** - sum_square
- def sum_square_difference(number)
- sq_sum = 0
- sum_of_sq = 0
- 1.upto(number) do |num|
- sq_sum += num #**2 on sq_sum later
- sum_of_sq += num**2
- end
- p (sq_sum**2) - sum_of_sq
- end
- p sum_square_difference(3) == 22
- # -> (1 + 2 + 3)**2 - (1**2 + 2**2 + 3**2)
- p sum_square_difference(10) == 2640
- p sum_square_difference(1) == 0
- p sum_square_difference(100) == 25164150
Add Comment
Please, Sign In to add comment