I'm looking for a program in the C language that can:
The problem is that I don't know when to stop the operation and I'm not sure if any number other than 2^x can equal 1 at the end but I think I'm wrong. Can someone help me?
One problem is that in the cycle finding process you could get some fairly big numbers that would overflow all built-in types of C.
Instead, you could solve the problem mathematically. There is a much harder, similar problem: https://en.wikipedia.org/wiki/Collatz_conjecture , but this one is easy. Consider that 3n + 3 = 3(n + 1)
- a multiple of 3. And a multiple of 3 cannot be a power of 2.
So, either the initial number is a power of 2 (then print "yes") or it can never become a power of 2 (print "no").
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>
int main() {
uint64_t n;
// get the input
scanf("%" SCNu64, &n);
// detect whether n is a power of 2
while(n > 1) {
if(n % 2 != 0) {
printf("no\n"); // not a power of 2
return 0;
}
n /= 2;
}
// is a power of 2
printf("yes\n");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.