Click here to Skip to main content
15,893,564 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
In this method, it must use the static nanoTime method of the java.lang.System class to time how long it takes to sum the first n integer values. It must print the number of nanoseconds after the loop.
At the moment the method i have, the numbers have already been added up before i start the time, so how could i change it so it is correct.

What I have tried:

Java
<pre>public static void timing(int n)
    {
        long sum = 0;
        for(int i = 1; i <= n; i++) {
            sum += i;
        }
        // Print out the time it took in nanoseconds.
        long startTime = System.nanoTime();
        long elapsedNanos = System.nanoTime() - startTime;
        System.out.println(elapsedNanos);
    } 
Posted
Updated 11-Dec-22 23:15pm

Maybe I'm missing something here, but wouldn't it make sense to put the "starttime" assignment above the loop?
 
Share this answer
 
Comments
CPallini 12-Dec-22 5:12am    
5.
Well, since sum is known to be
sum(n) = n(n+1)/2

Then your time estimation is quite correct...
:-D
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900