View difference between Paste ID: 5K6cZEDd and k09nmMGD
SHOW: | | - or go back to the newest paste.
1
public class ProjectEuler14
2
{
3
    public static void main(String[] args)
4
    {
5-
        double timeStart = System.currentTimeMillis();
5+
        final double TIME_START = System.currentTimeMillis();
6
7
        Collatz c = new Collatz();
8
        int highestNumOfTerms = 0;
9
        int currentNumOfTerms = 0;
10-
        int n = 0; //Value which produces most number of Collatz terms
10+
        int highestValue = 0; //Value which produces most number of Collatz terms
11
12
13
        for (double i = 1.; i <= 1000000.; i++)
14
        {
15
            currentNumOfTerms = c.startCollatz(i);
16
17
18
            if (currentNumOfTerms > highestNumOfTerms)
19
            {
20
                highestNumOfTerms = currentNumOfTerms;
21-
                n = (int)(i);
21+
                highestValue = (int)(i);
22-
                System.out.println("New term: " + n);
22+
                System.out.println("New term: " + highestValue);
23
            }
24
        }
25
26-
        double timeStop = System.currentTimeMillis();
26+
        final double TIME_STOP = System.currentTimeMillis();
27
28-
        System.out.println("Highest term: " + n + " with " + highestNumOfTerms + " number of terms");
28+
        System.out.println("Highest term: " + highestValue + " with " + highestNumOfTerms + " number of terms");
29-
        System.out.println("Completed in " + ((timeStop - timeStart)/1000) + " s");
29+
        System.out.println("Completed in " + ((TIME_STOP - TIME_START)/1000) + " s");
30
    }
31
}
32
33
34
public class Collatz
35
{
36
    private static int numOfTerms = 0;
37
    private boolean isFirstRun = false;
38
39
    public int startCollatz(double n)
40
    {
41
        isFirstRun = true;
42
        runCollatz(n);
43
        return numOfTerms;
44
    }
45
46
    private void runCollatz(double n)
47
    {
48
        if (isFirstRun)
49
        {
50
            numOfTerms = 0;
51
            isFirstRun = false;
52
        }
53
54
        if (n == 1)
55
        {
56
            //Do Nothing
57
            //Causes return to startCollatz()
58
        }
59
60
        else if (n % 2 == 0)
61
        {
62
            //Divides n by 2 following Collatz rule, running recursion
63
            numOfTerms = numOfTerms + 1;
64
            runCollatz(n / 2);
65
        }
66
67
        else if (n % 2 == 1)
68
        {
69
            //Multiples n by 3 and adds one, following Collatz rule, running recursion
70
            numOfTerms = numOfTerms + 1;
71
            runCollatz((3 * n) + 1);
72
        }
73
    }
74
}