Programming Homework Help
Programming Homework Help. Need to run this program in less than a minute: hailstone sequence
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 n2
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
}