http://www.cs.ecu.edu/~rws/c3300/prog1.pdf (for anyone that wants to view exactly whats needed for turn in)
Hello! I'm trying to write a c++ program that takes in the lower and upper limits of a bunch of numbers and output the length of the longest hailstone sequence. Posted below is what I have so far, but I always get the last number in the sequence for the longest length. I don't know how to make the transition to show the longest hailstone sequnce like it should be. Any help is appreciated!
//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>
using namespace 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 longest sequence is " << lengthHail(upper) << ".\n" << endl;
}
return 0;
}