Aditya
Aditya

Reputation: 3158

Sum square difference - What's wrong with my approach?

I see most of the people just loop around to add the numbers and their squares. I tried a different approach. Using the little mathematics I know, I realized I have a very efficient solution for it :

public static long sumOfNSquares(int N){
   // This is the standard mathematical formula I learnt in grade 10
    return (long) (N*(N+1)*(2*N+1))/6;
}
public static long squareofSum(int N){
   // Another standard mathematical formula. I took a square of it
    return (long) Math.pow( (N * N+1) /2, 2);
}

public static void main(String [] args){
    System.out.println(Math.abs(sumOfNSquares(100) - squareofSum(100)));
}

This uses the standard "Sum of N natural numbers" and "Sum of Squares of N numbers" formulae. Still I'm getting wrong answer. What might be wrong?

p.s. RESOLVED

Upvotes: 0

Views: 1817

Answers (5)

jack
jack

Reputation: 1

import java.util.*;

public class soq {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        long N = input.nextLong();

        while (N > 2) {
            long sumSquares = 0, sum = 0, difference = 0;

            for (int i = 1; i <= N; i++) {

                sum += i;

                sumSquares +=  Math.pow(i, 2);

            }

            difference =  (long) (Math.pow(sum, 2) - sumSquares);

            System.out.println(difference);

            N = input.nextInt();
        }
    }
}

Upvotes: 0

MohamedSanaulla
MohamedSanaulla

Reputation: 6252

You have to use brackets() to group the operations

return (long) Math.pow( (N * (N+1)) /2, 2);

Because, in Java * has a greater precedence over + and hence if there are no brackets then N*N is evaluated first. But what is expected is that N*(N+1) to be evaluated.

Upvotes: 0

Rob Lyndon
Rob Lyndon

Reputation: 12681

You need

public static long squareofSum(int N){
    // Another standard mathematical formula. I took a square of it
    return (long) Math.pow( (N * (N+1)) /2, 2);
}

This is a prototypical case in favour of Test Driven Development. Run a few obvious test cases through this method, and you'll save an awful lot of time when those mathematical typos creep into your code, as they are wont to do.

Gauss, who was a pioneer of series, was addicted to calculating examples. Perhaps it was problems like this that instilled the habit into him from an early age.

Upvotes: 0

voidMainReturn
voidMainReturn

Reputation: 3517

your N*N+1 looks wrong. * operator has a precedence over + operator hence it will be equal to (N*N)+1. So use N*(N+1)

Upvotes: 1

sadhu
sadhu

Reputation: 1479

Use this Math.pow( (N * (N+1)) /2, 2)

Use braces around N+1

Upvotes: 4

Related Questions