I'm new to programming and I wanted to see if A is equal to B after applying the following operations toward A.`
- If A=1, then A=A.
- If A is even, then A = A/2.
- If A is odd, then A = A*3 1.
output Yes if A is equal to B, No if it's not. I use the following code:
#include <stdio.h>
int main() {
int a, b;
scanf("%d %d", &a, &b);
getchar();
if (a == 1) {
a = a;
}
else if (a % 2 == 0) {
a = a / 2;
}
else if (a % 2 == 1) {
a = a * 3 1;
}
if (a == b) {
printf("Yes\n");
}
else {
printf("No\n");
}
return 0;
}
This works just fine, but I wanted to do the operation as much as possible. e.g. If A=12 and B=5 -> 12/2=6 ->6/2=3->3 2=5. thus A=B. What function do I use to do just that?
CodePudding user response:
This would be a good application for a while
loop:
while(a != 1 && a != b) {
if(a % 2 == 0) {
a = a / 2;
} else if(a % 2 == 1) {
a = a * 3 1;
}
}
if(a == b) {
printf("Yes\n");
} else {
printf("No\n");
}
Make sure that you understand the condition of the loop, which determines what "as much as possible" means, and why the final check is done outside the body of the loop.
The numbers 4 and 2 are implicitly part of any convergent sequence, since 4 = 3 * 1 1
and 2 = 4 / 2
. A complicated was to include them would be to let a
reach 1 twice before ending the loop. A simpler check would be to change the final if
to
if(a == b || b == 4 || b == 2) {
Since the Collatz conjecture is still an unsolved problem, there is no guarantee that the loop will converge in all cases. At the same time, it also implies that no one has been able to find a case for which a
doesn't at least reach unity.