Guest User

Untitled

a guest
Jan 22nd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. #Problem
  2. #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. #(3) == 22
  4. # -> (1 + 2 + 3)**2 - (1**2 + 2**2 + 3**2)
  5. # (n + n + n)**2 - (n**2 + n**2 + n**2)
  6.  
  7. #Examples:
  8. #sum_square_difference(3) == 22
  9. # -> (1 + 2 + 3)**2 - (1**2 + 2**2 + 3**2)
  10. #sum_square_difference(10) == 2640
  11. #sum_square_difference(1) == 0
  12. #sum_square_difference(100) == 25164150
  13.  
  14. #Data Types:
  15. #Input: an integer.
  16. #Output: an integer. sum of squares minus squares of sums
  17. #Structure: to_s.chars, map method, each, **upto method** or **times method**
  18.  
  19. #Algorithm/Logic:
  20. #sq_sum = 0
  21. #sum_square = 0
  22. #1.upto(integer) do |num|
  23. #sq_sum += num ##square sq_num later##
  24. #sum_squares += num**2
  25. #retrun sq_sum ** - sum_square
  26.  
  27. def sum_square_difference(number)
  28. sq_sum = 0
  29. sum_of_sq = 0
  30. 1.upto(number) do |num|
  31. sq_sum += num #**2 on sq_sum later
  32. sum_of_sq += num**2
  33. end
  34. p (sq_sum**2) - sum_of_sq
  35. end
  36.  
  37. p sum_square_difference(3) == 22
  38. # -> (1 + 2 + 3)**2 - (1**2 + 2**2 + 3**2)
  39. p sum_square_difference(10) == 2640
  40. p sum_square_difference(1) == 0
  41. p sum_square_difference(100) == 25164150
Add Comment
Please, Sign In to add comment