Hello I have just started learning programming & this problem is really stumping me. I have to do a syracuse sequence (explained below) & I know my code below is very wrong, (it needs to use for statements in there) but can you give me any advice on what to do?
Let n be a positive integer and f(n) be the transformation that sends n to n/2 if n is even, and sends n to 3n+1 if n is odd. Starting with a positive value u called the seed, the sequence of integers iteratively generated by f
and u is called a Syracuse sequence.For example, starting with the seed u = 1, the subsequent terms of the sequence are 4, 2, and 1.
The length of the sequence (excluding the seed) is therefore 3.For u = 4, the next terms are 2 and 1. The length is 2.
For u = 404, the next terms are 202, 101, 304, 152, 76, 38, 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40,
20, 10, 5, 16, 8, 4, 2, and 1. The length is 27.Some examples of the program execution are as follows. The entered value is shown in bold.
Example 1
Enter a positive number: 4
The sequence length is: 2
The maximum is: 2Example 2
Enter a positive number: 12
The sequence length is: 9
The maximum is: 16
#include <iostream>
#include <string>
using namespace std;
int check_odd(int& n); //checks if n is an even or odd number then does syracuse fucntion
int main()
{
int n;
cout << "Enter a positive number: ";
cin >> n;
cout << "n= "<< n << endl;
check_odd(n);
return 0;
}
int check_odd(int& n)
{
int co = 0; // variable to count how many times the equation n/2 or 3n + 1 is done
while (n >= 1)
if (n % 2 == 0) {
cout << "The number " << n << " is even" << endl;
n = (n/2);
co++;
cout << "f(n) = " << n << " co = "<< co << endl;
}
else if (n % 2 != 0) {
cout << "The number " << n << " is odd" << endl;
n = ((3 * n) + 1);
co++;
cout << "f(n) = " << n << " co = "<< co << endl;
}
}
I have broken it up into smaller problems, ie
--check whether n is an even or odd number - I can do that
-- if odd, perform 3n + 1 , if even, n/2 (expression) - kindof can do this
-- if n is greater than 1, count how many times the expression is performed. - Not working at all