1,105,214 Community Members

Need help finding time with System.currentTimeMillis()

Member Avatar
macdunk11
Newbie Poster
20 posts since Jan 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I am finding the factorial and exponents of variables both recursively and iteratively. What I need help with is finding out how long it took each one. Where do I put the System.currentTimeMillis() part and how do I find out exactly how long it took (i.e. 55 milliseconds)?

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("What integer do you want to get the factorial of?");
    int n = scan.nextInt();
    System.out.println("The Recursive factorial of " + n + " is " + recur(n) + ".");
    System.out.println("The Iterative factorial of " + n + " is " + iter(n) + ".");
    System.out.println("What two integers do you want to get the exponent of? (a to the x)");
    int a = scan.nextInt();
    int x = scan.nextInt();
    System.out.println("The Recursive exponent of " + a + " is " + recurs(a, x) + ".");
    System.out.println("The Iterative exponent of " + a + " is " + itera(a, x) + ".");
}

public static int recur(int n){
    if(n == 0){
        return 1;
    }
    else
    return n * recur(n-1);
}

public static int iter(int n){
    if (n <= 1) {
        return 1;
    }
    int it = n;
    for (int i = n - 1; i > 1; --i) {
        it *= i;
    }
    return it;
}

public static int recurs(int a, int x){
    if (x == 0)
        return 1;
    else if (x == 1)
        return a;
    else
        return a * recurs(a, x-1);
}

public static int itera(int a, int x){
    int r = a;
    if (x == 0)
        return 1;
    else if (x == 1)
        return a;
    else
    for (int i = 1; i <= x; i ++){
        r *= a;
    }
    return r;
}
Member Avatar
NormR1
Posting Sage
7,723 posts since Jun 2010
Reputation Points: 563 [?]
Q&As Helped to Solve: 793 [?]
Skill Endorsements: 16 [?]
Team Colleague
 
0
 

how do I find out exactly how long it took

Get the starting time and save it in a long variable. When done, get the current time and subtract from it the starting time to get how long it took.

Member Avatar
macdunk11
Newbie Poster
20 posts since Jan 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Ok, thanks!

Question Answered as of 2 Years Ago by NormR1
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article