Hey all -- have the following question from a problem set:
The hailstone function must be recursive.
A hailstone sequence starts with a given integer. If that integer is even, then you divide it by two to get the next integer in the sequence, but if it is odd, then you multiply it by three and add one to get the next integer in the sequence. Then you use the value you just generated to find out the next value, according to the same rules. Write a function that takes the starting integer as a parameter and returns how many steps it takes to reach 1 (technically you could keep going 1, 4, 2, 1, 4, 2, etc. but we will stop when you first reach 1). If the starting integer is 1, the return value should be 0, since it takes no steps to reach one (we're already there). If the starting integer is 3, then the sequence would go: 3, 10, 5, 16, 8, 4, 2, 1, and the return value should be 7.
The main method should prompt the user for a positive integer (no input validation required), pass it to the function and print out the return value.
I got the following code so far, but I can't save it because there is an error on line 22 (also marked in code) -- hailstone.cpp:32: error: statement cannot resolve address of overloaded function
Not sure why it's overloaded, since the loop has an end point. Any help here?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include<iostream>
using namespace std;
int hailstone(int num)
{
if (num == 1)
{
return 0;
}
if (num%2==0)
{
num = num/2;
}
else
{
num = num*3 + 1;
}
return 1 + hailstone(num);
}
int main()
{
int n;
cout << "Enter n: " << endl;
cin >> n;
cout << "Number of steps to 1 is: " << hailstone(n); endl; //error overloaded function
return 0;
}
|