简体   繁体   中英

Looking for a C program that can detect whether a sequence similar to the Collatz conjecture terminates or not

I'm looking for a program in the C language that can:

  • scan an unsigned number that can be as big as 10^14
  • if it is even divide it by 2
  • otherwise replace it with 3*n+3 (n being the number that is scanned) so that it becomes an even number
  • do this as many times as needed to see if it is equal 1 at the end. If it is, print "yes", otherwise print "no".

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM