/* next(n) prints the hailstone sequence starting at n. next(1) will never be
computed by the program since no number follows 1 in the hailstone sequence. */
int next(int n)
{
int i = n;
while(i != 1)
{
if(i % 2 == 0)
{
i = i/2;
}
else
{
i = 3 * i + 1;
}
return (i);
}
}
//printHailstone(n) prints the hailstone sequence starting at n.
void printHailstone(int n)
{
int i = n;
if(i == 1)
{
printf("%i ", i);
}
else
{
printf("%i ", i);
printHailstone(next(i));
}
}
// length(n) returns the length of the hailstone sequence of n.
int length(int n)
{
int length = 1;
if(n == 1)
{
return 1;
}
while(n != 1)
{
n = next(n);
length= length+1;
}
return length;
}
/* hailstoneMax(n) returns the largest number in the hailstone sequence
starting with n. */
int hailstoneMax(int n)
{
int maxNum = 0;
if(n == 1)
{
return n;
}
while(n != 1)
{
if(n > maxNum)
{
maxNum = n;
}
n = next(n);
}
return maxNum;
}
/* longestHailstone(n) returns the longest of the hailstone sequences that
start with numbers from 1 to n. */
int longestHailstone(int n)
{
int longest = 1;
for(int i = 1; i < n; i++)
{
if(length(i+1) > length(i))
{
longest = length(i+1);
}
}
return longest;
}
/* firstOfLongest(n) returns the first number of the longest hailstone sequence
that starts with numbers from 1 to n. */
int firstOfLongest
int count = 1;
{
int i = 1;
while(i < n)
{
if(length(i+1) > length(i))
{
count = count+1;
}
i++;
}
return count;
}
The output for 3 is:
What number do you want to start the hailstone sequence with?
3
You are starting the hailstone sequence with 3.
3 10 5 16 8 4 2 1
The length of the hailstone sequence is 8.
The largest number in the sequence is 16.
The longest sequence starting with a number from 1 to 3 has a length of 8.
The longest sequence starting with a number from 1 to 3 begins with 3.
Anything above 3 is usually incorrect on the last line of the output, for example 9 gives an output of 7 on the last line and 7 and 8 give an output of 6 on the last line.
What am I doing wrong for that last portion?(I have to only use loops for this assignment.)