60.1k views
5 votes
Write a program to find and print the sum of the first n cubes in the following four ways.

Declare a variable n and ask the user for a value. Print the value of n.
1. Send n to a method to compute sum1 = 1^3 + 2^3 + … + n^3
2. Send n to a method to compute sum2 = n^2 (n + 1)^2 / 4
3. Send n to a method to compute sum3 = (1 + 2 + … + n)^2 . This is (the sum of the first n integers)^2 .
4. Compute sum4 = n (n +1)(2n + 1) / 4 + 2 ). You must program it this way without simplifying

User Qwertzman
by
4.9k points

1 Answer

3 votes

Answer:

The solution code is written in Java.

  1. public class Main {
  2. public static void main(String[] args) {
  3. System.out.print("Please enter a number: ");
  4. Scanner console = new Scanner(System.in);
  5. int n = console.nextInt();
  6. calculateSum1(n);
  7. calculateSum2(n);
  8. calculateSum3(n);
  9. calculateSum4(n);
  10. }
  11. public static void calculateSum1 (int num){
  12. int sum1 = 0;
  13. for(int i=1; i <= num; i++){
  14. sum1 += i*i*i;
  15. }
  16. System.out.println("Sum 1 : " + sum1);
  17. }
  18. public static void calculateSum2 (int num){
  19. int sum2 = num * num * (num + 1) * (num + 1) / 4;
  20. System.out.println("Sum 2 : " + sum2);
  21. }
  22. public static void calculateSum3 (int num){
  23. int sum3 = 0;
  24. for(int i=1; i <=num; i++){
  25. sum3 += i;
  26. }
  27. sum3 = sum3 * sum3;
  28. System.out.println("Sum 3 : " + sum3);
  29. }
  30. public static void calculateSum4 (int num){
  31. int sum4 = (num * (num + 1) * (2*num + 1)) / (4+2);
  32. System.out.println("Sum 4 : " + sum4);
  33. }
  34. }

Step-by-step explanation:

Firstly we create four different methods that calculate the sum of the first n cubes in different ways (Line 13 - 43).

This is important to understand the concept of operator precedence to work out the different ways of summation.

For example, The operator * and / will always have higher precedence than +.

On another hand, any expression enclosed within the parenthesis will have highest precedence and therefore the value will be evaluated prior to others.

This is also important to understand the expression evaluation will always start from left to right.

User Ayjay
by
5.9k points