Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I believe there is a logical math problem with my code, but I cannot put my finger where is it and why

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;             
}                                            
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading