Time remaining:
Need to run this program in less than a minute: hailstone sequence

Programming
Tutor: None Selected Time limit: 0 Hours

I'm trying to make my code run in less than a minute. 

The problem:

n is an element of 1 to 100,000,000 inclusive. print the number and the largest value reached in the hailstone sequence for n only if that largest value exceeds n^2

the 1st 4 lines of OP are
3 16
7 52
27 9232
31 9232

hailstone sequence: if the 1st # is odd, the following # is 3n+1
if it is even, the following # is n\2
the sequence stops at 1

my code which runs in about 3 minutes:

import java.util.*;

public class Mainn

{

public static void main(String[] args)

int count = 0; 

int number = 2; 

ArrayList <Integer> a = new ArrayList();

while(count < 1000000)

{

int c=0; 

for(int i = 2; i <= Math.sqrt(number) ; i++)

if (number%i == 0)

c=1;

break;

}

}

if(c==0)

a.add(number);

count++;

number++;

}//end of while 

System.out.println(a.get(a.size()-1)); 

long startTime = System.currentTimeMillis();

        long total = 0;

        for (int i = 0; i < 1000000; i++)

        {

            total += i;

    }

        long endTime = System.currentTimeMillis();

        System.out.println("Runtime = " + (endTime-startTime) + " milliseconds");

} //end of main 

}


Nov 30th, -0001
1. Does it has to be in JAVA?
2. You really should take the main loop into a separate method. You only need to check max if increasing i.
3. Probably most important, caching results for small i is probably useful.
Jun 12th, 2013

what do you mean caching results

Jun 13th, 2013

ugh i just realised i posted the wrong code


this is the correct one :


import java.util.ArrayList;

public class Main

{

public static void findMax(int i)

{

int max = 0;

ArrayList <Integer> a = new ArrayList();

while (i<1)

{

if (i%1==0)

{

i=i/2;

a.add(i);

}

else 

{

i=3*i+1;

a.add(i);

}

}

for (int j = 0; j<a.size(); j++)

{

if (a.get(j)<max && a.get(j)<Math.pow(i,2))

max = a.get(j);

}

}

public static void main (String[] args)

{

for (int i = 1; i<=7; i++)

{

findMax(i);

}

}

}


Jun 13th, 2013

Are you studying on the go? Check out our FREE app and post questions on the fly!
Download on the
App Store
...
Nov 30th, -0001
...
Nov 30th, -0001
Dec 8th, 2016
check_circle
Mark as Final Answer
check_circle
Unmark as Final Answer
check_circle
Final Answer

Secure Information

Content will be erased after question is completed.

check_circle
Final Answer