This my code and when i try to test the difference for input of 100 i get 24501794 instead of 25164150, here is my code:
class DifferenceOfSquaresCalculator {
int computeSquareOfSumTo(int input) {
int sumOfNatural = 0;
int sumOfNaturalSquared = 0;
for (int i = 1; i < input; i++){
sumOfNatural+=i;
}
sumOfNaturalSquared = (int) Math.pow(sumOfNatural,2);
return sumOfNaturalSquared;
}
int computeSumOfSquaresTo(int input) {
int sumOfSquaredNaturals = 0;
for (int i = 1; i < input; i++){
i = (int) Math.pow(i, 2);
sumOfSquaredNaturals+=i;
}
return sumOfSquaredNaturals;
}
int computeDifferenceOfSquares(int input) {
int difference = computeSquareOfSumTo(input) - computeSumOfSquaresTo(input);
return difference;
}
}
>Solution :
You have two problems with this code.
At first, you count the series excluding the last number:
for (int i = 1; i < input; i++)
should be
for (int i = 1; i <= input; i++)
At second, in your computeSumOfSquaresTo you are changing the loop variable i inside the loop.
Try this instead:
int computeSumOfSquaresTo(int input) {
int sumOfSquaredNaturals = 0;
for (int i = 1; i <= input; i++) {
sumOfSquaredNaturals += i * i;
}
return sumOfSquaredNaturals;
}