How to sum array contents with their powers of 3

1.9k views Asked by At

I need to do something like this - user types in a number (e.g. 5) and the program shows the result of the following action: 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 + 5*5*5. My code is following:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter your number:");
    int n = input.nextInt();

    int a[] = new int[n];
    int power = 0;
    int sum = 0;

    for (int i = 1; i <= a.length; i++)
    {
        power = (int) pow(i, 3);

        // Maybe here'a the problem, a[n] has not enough space for the power (???)
        sum += a[power];
    }
    System.out.println(Result: " + sum);
}

I think that I understand why this code doesn't work but I will appreciate any ideas about how to do it properly and runnable.

5

There are 5 answers

1
rainkinz On

Change:

sum += a[power];

to

a[i-1] = power;
sum += a[i-1];

or forget the array altogether

sum += power;
0
Konstantin Yovkov On

sum += a[power]; doesn't exist.

You need to :

  1. store the power value in the ith array item.
  2. add the ith array value to the sum

Change your loop body to:

power = (int) pow(i, 3);
a[i - 1] = power;
sum += a[i - 1];
0
Flavio On

sum += power;, no need for a.

4
Mike 'Pomax' Kamermans On

You're doing way too much work.

Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt(),
    sum = 1;
for (int i=2; i<=n; i++) {
  sum += (int) Math.pow(i,3);
}

done. sum now contains the sum 1³ + 2³ + 3³ + ...

Or, more efficiently with exactly the same functionality:

Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt(),
    sum = 1;
while(n > 1) {
  sum += (int) Math.pow(n--,3);
}

Why? Because 1 + 5³ + 4³ + 3³ + 2³ is the same as 1³ + 2³ + 3³ + 4³ + 5³

Of course you could also just directly compute that value, using actual maths, cutting all the entire algorithm with a simple arithmetic oneliner.

4
Alexis C. On

Or simply use math :

enter image description here

int n = input.nextInt();
int result = (int)(0.25 * Math.pow(n, 2)*Math.pow(1+n,2));

Or even more simple, as @ajb said :

int result = n*n*(n+1)*(n+1)/4;