Hello! I am stuck trying to figure out the last couple of things for this program. The program is supposed to read in a lower and upper limit, produce the hailstone sequence and length for each number, then determine which sequence is the longest.
I can't figure out how to get the longest sequence and for some reason the length is always whatever the last number in the limits is. Any help is appreciated and the code should be below.
//Justin Chestnutt
//CSCI 3300
//Program 1
//Program reads in user input for upper and lower limits to print out hailstone sequence for numbers in the limit range and determine the longest sequence.
#include <iostream>
usingnamespace std;
//Hailstone sequence takes any number as an input and divides it by 2 if the number is even otherwise multiply by 3 and add 1 if the number is odd.
//The idea is that no matter what the user inputs you will eventually come to the answer of 1 at the end of the sequence.
//Hailstone function takes the input of the current number then calculates the next number in the hailstone sequence
int Hailstone(int n)
{
if(n % 2 == 0)
{
n /= 2; //number is even
}
else
{
n = 3 * n + 1; //number is odd
}
return n; //returns the value
}
//Calculates length of the hailstone sequence
int lengthHail(int num)
{
int count = 1;
while(num != 1)
{
num = Hailstone(num);
count++; //adds one to count everytime a calculation is done
}
return count;
}
//Ask for user input and reads in two integers that represent the lower limit and upper limit.
int main()
{
int lower, upper;
int count = 0;
cout << "Enter Lower Limit.\t";the
cin >> lower;
cout << "Enter Upper Limit.\t";
cin >> upper;
for(int i = lower;i <= upper; i++)
{
lower = i;
while(lower != 1)
{
cout << " " << Hailstone(lower) << " " << endl;
lower = Hailstone(lower);
count++;
}
cout << "\nLength of sequence is " << lengthHail(upper) << ".\n" << endl;
}
return 0;
}
Why are you changing your lower bound variable during the for loop? Isn't it just supposed to represent where you start testing sequences?
You go through the Hailstone sequence using lower, which ends up being 1 after the first loop.
After this the while condition never evaluates true.
Also, you print lengthHail(upper) every time the for loop runs. Just write a loop that iterates through lower-upper, and tests the length of each number, and if it is greater than some variable (int result) which stores the longest sequence length, save it.
Honestly, this is my second week of programming and I don't even know how i got this far. If you don't mind if you could be extremely specific with your response I would appreciate it. I hate to say "write whatever i'm doing wrong how it should be" but I almost need it in order to analyse for future use.