Write a simple program showing that a for loop that adds up 2 x N numbers will t
ID: 3875834 • Letter: W
Question
Write a simple program showing that a for loop that adds up 2 x N numbers will take twice as long as one that adds up N numbers, for large enough values of N. To time this code, you should place calls like System.nanoTime() before and after the loop, and subtract the first from the second to calculate the elapsed time. Your program should print N and the time in milliseconds taken by the loop, for 4 values of N, showing that the times double (roughly) when N is doubled. (In the case of nanoTime you should divide the result by 1E6to convert from nanoseconds to milliseconds.) This program will need very large values for N. On mine I used values 100000000, 200000000, 400000000 and 800000000.
Explanation / Answer
This code lets the user input a really large value for n . And then computes the sum for 0 to n and 0 to 2*n ;
Displays the time separately taken to compute the sum from 0 to n and 0 to 2*n . Typically for a really large value of n we can see that the execution time almost double from n to 2*n .
import java.util.Scanner;
public class alpha {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
long N ;
long sum=0;
System.out.println("Input a large value of n : ");
N = sc.nextLong();
long startTime = System.nanoTime();
for(int i=0;i<2*N;i++)
{
sum = sum + i;
}
long stopTime = System.nanoTime();
long time = stopTime-startTime;
time = time/1000000;
System.out.println("Time to execute sum of 2*n : "+time);
startTime = System.nanoTime();
for(int i=0;i<N;i++)
{
sum = sum + i;
}
stopTime = System.nanoTime();
time = stopTime-startTime;
time = time/1000000;
System.out.println("Time to execute sum of n : "+time);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.