0

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

4

5 回答 5

4

用这个Math.pow( (N * (N+1)) /2, 2)

使用大括号N+1

于 2013-07-05T11:19:30.763 回答
1

N*N+1看起来不对。* 运算符优先于 + 运算符,因此它将等于(N*N)+1. 所以使用N*(N+1)

于 2013-07-05T11:21:40.350 回答
0

你需要

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);
}

这是一个支持测试驱动开发的典型案例。通过这种方法运行一些明显的测试用例,当这些数学错别字潜入您的代码时,您将节省大量时间,因为它们不会这样做。

高斯是级数的先驱,他沉迷于计算样例。或许正是这样的问题,才让他从小养成了这种习惯。

于 2013-07-05T11:21:18.413 回答
0
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();
        }
    }
}
于 2015-04-03T16:34:26.007 回答
0

您必须使用括号()对操作进行分组

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

因为,在 Java 中 * 比 + 具有更高的优先级,因此如果没有括号,则首先评估 N*N。但预期的是要评估 N*(N+1)。

于 2013-07-05T11:25:25.967 回答