I'm doing a homework assignment where we're testing the runtime of a couple algorithms (greatest common divisor, or GCD) using 10-digit prime numbers.
We are to capture the runtime as milliseconds, which I capture using System.currentTimeMillis()
.
The way I do it is to have a start time variable and a stop time variable, then find the difference between those two in another variable.
So far, it works perfectly for one method, but returns 0 or 1 for the other method.
I went through the debugger, and it seemed to work correctly, but when I run it, it returns 0 or 1.
Here are the variables I'm using and the main method. The commented-out line works as intended, but the fastgcd
method is the one that returns 0 or 1.
public class GCD {
public static long startTime;
public static long stopTime;
public static long elapsedTime;
public GCD(){
}
public static void main(String[] args){
startTime = System.currentTimeMillis();
//System.out.println(gcd(3267000013L, 1500450271L));
System.out.println(fastgcd(3267000013L, 1500450271L));
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
System.out.println(Long.toString(elapsedTime));
}
Here's the method that works:
public static String gcd(long a, long b) {
long n = Long.min(a, b);
for (long i = n; i >= 1; i--) {
if (a % i == 0 && b % i == 0) {
return "Done";
}
}
// If error
return null;
}
And here's the method that doesn't work:
public static String fastgcd(long a, long b){
if(b == 0){
return "Done";
}
else{
return fastgcd(b, a%b);
}
}
So for the method that works, I will get somewhere between 12000 - 12500 milliseconds for a 10-digit number.
The fastgcd
method returns 0 or 1 milliseconds, which isn't right, especially a 10-digit prime number.
No idea where it's going wrong...