What to do Write a C program that implements the \"3A+1\" algorithm. This algori
ID: 3754157 • Letter: W
Question
What to do Write a C program that implements the "3A+1" algorithm. This algorithm works like so: starting with a given integer number, the algorithm determines whether the number is odd or even. If it is odd, it computes 3 times the original number plus one, as the name 3A+1 suggests. If the number is even, it is divided by 2. In either case, the result is being assigned back to the variable that contained the original number. The process keeps going until a result of 1 is achieved, at which point the algorithm terminates. Interesting fact: although this algorithm is very simple to explain, and run, nobody could ever prove that it actually terminates. For our purposes we just assume it does! Here is a sample run of the algorithm for an initial number of 7 7- 2211 34 - 17 -52-26- 13- 40->20- 10->5-> 16-8-4-2->1 As you can see, the algorithm ran though 16 iterations until it reached 1. In your implementation of the algorithm I want you to un it on all natural numbers, starting at 1, up to and including some value MAX. ask you to implement MAX as a symbolic constant using a #denne preprocessor directive. For each run, you are supposed to print out the original number and how many terations it took to eventually reach1Explanation / Answer
#include <stdio.h>
#define MAX 7
static int numberOfIterations = 0;
int threeAPlusOne(int n){
if(n==1)
return numberOfIterations;
if(n%2==0){
numberOfIterations++;
return threeAPlusOne(n/2);
}
else {
numberOfIterations++;
return threeAPlusOne( (3*n)+1 );
}
}
int main() {
int i =1;
for(;i<=MAX;i++){
printf("%d : %d ",i,threeAPlusOne(i) );
numberOfIterations =0;
}
return 0;
}
Let me know you need any help in any part of the code.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.