For Loop Sum Counter
public void sumCheck1(int a){
if (a > 0){
int b = 0;
for (int i = 0; i <= a; i++){
b = b + i;
}
print(b);
}else if (a < 0){
int b = 0;
for (int i = 0; i >= a; i--){
b = b + i;
}
print(b);
}else{
print(0);
}
}
Equation Sum Counter
public void sumCheck2(int a){
if (a > 0){
int b = (((a/2) * (a-1)) + a);
print(b);
}else if (a < 0){
int b = (((a/(0-2)) * (a+1)) + a);
print(b);
}else{
print(0);
}
}
Full Code
import java.util.*;
import java.lang.*;
import java.io.*;
class MathTimings
{
public static void main (String[] args){
sumCheck1(1);
sumCheck1(100);
sumCheck1(-1);
sumCheck1(-100);
sumCheck1(0);
sumCheck2(1);
sumCheck2(100);
sumCheck2(-1);
sumCheck2(-100);
sumCheck2(0);
}
public static void sumCheck1(int a){
long start = System.nanoTime();
if (a > 0){
int b = 0;
for (int i = 0; i <= a; i++){
b = b + i;
}
long stop = System.nanoTime() - start;
System.out.println(b + " | " + stop);
}else if (a < 0){
int b = 0;
for (int i = 0; i >= a; i--){
b = b + i;
}
long stop = System.nanoTime() - start;
System.out.println(b + " | " + stop);
}else{
long stop = System.nanoTime() - start;
System.out.println(0 + " | " + stop);
}
}
public static void sumCheck2(int a){
long start = System.nanoTime();
if (a > 0){
int b = (((a/2) * (a-1)) + a);
long stop = System.nanoTime() - start;
System.out.println(b + " | " + stop);
}else if (a < 0){
int b = (((a/(0-2)) * (a+1)) + a);
long stop = System.nanoTime() - start;
System.out.println(b + " | " + stop);
}else{
long stop = System.nanoTime() - start;
System.out.println(0 + " | " + stop);
}
}
}
Timings:
Type | Number | Sum | Time |
---|---|---|---|
For-Loop | 1 | 1 | 813 nanoseconds |
For-Loop | 100 | 5050 | 2829 nanoseconds |
For-Loop | -1 | -1 | 677 nanoseconds |
For-Loop | -100 | -5050 | 2765 nanoseconds |
For-Loop | 0 | 0 | 410 nanoseconds |
Equation | 1 | 1 | 597 nanoseconds |
Equation | 100 | 5050 | 495 nanoseconds |
Equation | -1 | -1 | 514 nanoseconds |
Equation | -100 | -5050 | 488 nanoseconds |
Equation | 0 | 0 | 425 nanoseconds |