C PROGRAMMING Count the number of steps needed to reach 1 for a positive integer
ID: 3886519 • Letter: C
Question
C PROGRAMMING
Count the number of steps needed to reach 1 for a positive integer n that
uses the following rule: if n is odd, replace it with 3n + 1 and if n is
even, replace it with n/2. Call this function countSteps. Its signature is
// Count the number of steps needed to reach 1 for positive integer n with
// the above rule.
int countSteps( int n )
For example for n = 3, the rule produces 10, 5, 16, 8, 4, 2, 1 and the
number of steps is 7.
For n = 7, the rule produces 22, 11, 34, 17, 52, 26, 13, 40, 20, 10,
5, 16, 8, 4, 2, 1 and the number of steps is 16.
a) Design an efficient algorithm for countSteps().
b) Design an efficient algorithm that finds the number between two integers
low and high with maximal value for its countSteps().
Explanation / Answer
Please find the required solution for a.
#include <stdio.h>
int countSteps(int n)
{
int numberOfSteps = 0;
while (n>1)
{
if(n%2 == 0)
n = n/2;
else
n = 3*n+1;
printf("%d ", n);
numberOfSteps++;
}
return numberOfSteps;
}
int main()
{
printf(" number of steps for %d to reach 1 is %d ", 3, countSteps(3));
printf(" number of steps for %d to reach 1 is %d", 7, countSteps(7));
return 0;
}
sample output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.