I am doing an assignment where I must use nested loops in order to add up the squares and cubes of integers from 1 to N (N being whatever the user inputs). For example, if the user input the number 5, the program is supposed to do "1² 2² 3² 4² 5²" and output the sum of those numbers, as well "1³ 2³ 3³ 4³ 5³" and output the sum of those numbers.
However, I am having trouble figuring out how to code it in a way that I receive the proper output? This is what I wrote. Scanners were already added.
int limitNum = input.nextInt();
double squareNums:
double sumofSq = 0;
double cubedNums;
double sumofCubes = 0;
for(int s = 1; s <= limitNum; s )
{
for(int c = 1; c <= limitNum; c )
{
cubedNums = Math.pow(c, 3);
sumofCubes = sumofCubes cubedNums;
}
squareNums= Math.pow(s, 2);
sumofSq = sumofSq squareNums;
}
But currently, when I run this program, the sum of the squares output correctly, but the sum of the cubes is always some big number. For example if 5 is used, sumofSq would output 55.0, but sumofCubes would output 1125.0.
CodePudding user response:
There is no point using a nested loop as this would result in complexity of O(n²)
. A single loop would be sufficient and be in complexity class O(n)
.
public class Application {
public static void main(String[] args) {
var squareSum = 0d;
var cubeSum = 0d;
var upperBound = 5;
for(var i = 1; i <= upperBound; i ){
squareSum = Math.pow(i, 2);
cubeSum = Math.pow(i, 3);
}
System.out.printf("""
Sum of first n squares: %s
Sum of first n cubes: %s
""", (int)squareSum, (int)cubeSum);
}
}
In fact there is no need to loop at all => constant computation time no matter the size of the input O(1)
. There is a well known formula which tells you the sum of the first n
squares.
n(n 1)(2n 1)
------------
6
Please see this for a proof.
The same holds true for the first n
cubes.
n²(n 1)²
--------
4
Please see this for a proof.
The following program will therefore return the same result.
public class Application {
public static void main(String[] args) {
var upperBound = 5;
System.out.printf("""
Sum of first n squares: %s
Sum of first n cubes: %s
""", sumOfFirstNSquares(upperBound), sumOfFirstNCubes(upperBound));
}
public static int sumOfFirstNSquares(int n){
return (n * (n 1) * (2 * n 1)) / 6;
}
public static int sumOfFirstNCubes(int n){
return ((n * n) * (n 1) * (n 1)) / 4;
}
}
CodePudding user response:
In fact there is no need to loop at all => constant computation time no matter the size of the input O(1). There is a well known formula which tells you the sum of the first n squares.
java