Suppose that the first number of a sequence is x, in which x is an integer. Defi
ID: 3905316 • Letter: S
Question
Suppose that the first number of a sequence is x, in which x is an integer. Define a0 = x; an+ 1 = an/ 2 if an is even; an+ 1 = 3 an + 1 if an is odd. Then, there exists an integer k such that ak = 1. Write a program that prompts the user to input the value of x. The program output the integer k such that ak = 1 and the numbers a0, a1, a2, . . . , ak. ( For example, if x = 75, then k = 14, and the numbers a0, a1, a2, . . ., a14, respectively, are 75, 226, 113, 340, 170, 85, 256, 128, 64, 32, 16, 8, 4, 2, 1.) Test your program for the following values of x: 75, 111, 678, 732, 873, 2048, and 65535.
No documentation (-5)
Weak documentation (-3)
Should include a clear prompt for how to start by entering an integer, x (-2 if not)
Needs a while loop or do while to calculate the new value of x each iteration of the loop (-6 if not, or if for loop used)
Must have an if/else if or if/else within the while to determine if x is even or odd (-3 if not)
Each iteration of the loop, should output the value of x (-8 if not attempting to output x)
After the loop, output k (clearly labeled) (-6 if k is not output at all, -2 if not clearly labeled)
Inefficiencies, up to –5 and noted why
TEST: Use the integer 13 for x. Output should be: 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 and k is 9 (-6 if output of x values is incorrect) and (-5 if k is incorrect)
Explanation / Answer
#include <iostream>
using namespace std;
int main(){
int x;
int count;
cout << "Enter x:";
cin >> x;
count = 0;
while(x != 1){
cout << x << " ";
if (x % 2 == 0)
x = x/2;
else
x = 3*x + 1;
count++;
}
cout << x << endl;
cout << "k=" << count << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.