English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I am trying to figure out how to make a program that would output hailstone numbers.

The criteria is:
If the number is even, divide it in half
If the number is odd, multiply it by 3 then add 1
If the number reaches 1, stop.

So far, I have this:

if(Num % 2 == 0)
{
while(Num % 2 ==0)
{
cout << Num << endl;

Num = Num / 2;
}
cout << Num << endl;
}

if(Num % 2 == 1)
{
while(Num % 2 == 1)
{


Num = (Num * 3) + 1;
}
cout << Num << endl;
}

How do I make it so that the program will end if one of the numbers turns out to be 1?

Thanks.

2007-01-24 03:37:08 · 2 answers · asked by Defcon6 2 in Computers & Internet Programming & Design

Nevermind, I was able to get the program to stop if/when the output goes to 1.

However, how do I make it so that the if statements will repeat if the output is an even or odd number?

2007-01-24 03:47:19 · update #1

2 answers

you'd probably be better off doing this recursively, something along the lines of:

int hailStone(int n)
{
cout< if (n > 1)
{
if (n % 2 == 1)
hailStone((n*3)+1);
else
hailStone(n/2);
}
}

then make an initial call to the function with your seed.

2007-01-24 03:48:37 · answer #1 · answered by Boofie 6 · 0 0

This algorithm is not suited for use with a recursive function. First, a recursive function should only be used to calculate an undetermined value or a path to a value. Second, this algorithm can take upwards of 50 iterations before it reaches the value of 1. If you were to use a recursive function, you would only eat up memory.

Here is a simple WHILE loop that does what you want.

while( N != 1) {

cout << N << " ";
if( N % 2) {
N = (N * 3) + 1;
} else {
N /= 2;
}
}

2007-01-24 13:46:17 · answer #2 · answered by Kookiemon 6 · 0 0

fedest.com, questions and answers