Skip to main content
Code Review

Return to Revisions

2 of 2
Commonmark migration

Method extraction.

Even for simple programs, having multiple responsibilities in a method is poor practice.

Consider simple extractions, like:

private static int squareOfSum(int limit) {
 int sum = (limit * (limit + 1)) / 2;
 return sum * sum;
}
public static int sumOfSquares(int limit) {
 int sum = 0;
 for (int i = 1; i <= limit; i++) {
 sum += i * i;
 }
 return sum;
}

Then your main method becomes:

int difference = squareOfSum(100) - sumOfSquares(100);
System.out.printf("Difference is %d\n", difference);

By extracting functions, the logic becomes reusable, and discrete. Much better.

Additionally, it allows you to easily change the logic inside the methods to suite your algorithms, and use better algorithms like vnp suggests (+1 to that answer too).

Timing

Your use of the nanos to time your code is misleading. The performance of the code is heavily related to how often the code runs, and, for this example, any performance measurement is unreliable....

rolfl
  • 98.1k
  • 17
  • 219
  • 419
default

AltStyle によって変換されたページ (->オリジナル) /