简体   繁体   中英

How can I decrement numbers in Collatz conjecture program in C

Currently I am implementing the Collatz conjecture problem in the C language. I am able to print the series of a particular digit. For instance if number is 25 then series is something like 25 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 = 24 . 24 is the number of elements in the series. Now I want to print the number of series till 1 . like 25,24,... to 1 .

Here is what I have tried:

#include <stdio.h>

int main() {
    long x, a = 0;

    printf("Enter the value of X:");
    scanf("%lu", &x);
    printf("%ld ", x);

    for (i = x * x; i >= 1; i--) {
        if (x % 2 == 0) {
            x = x / 2;
            printf("%lu ", x);
            if (x == 1) {
                break;
            }
        } else {
            x = (3 * x) + 1;
            printf("%lu ", x);
            if (x == 1) {
                break;
            }
        }   
        a++;
    }
    printf(" = %lu\n", a + 2);
    return 0;
}

Please help me with this problem.

A good idea would be to have the Collatz function for 1 element in a function. This function would take a parameter of the element that eg 25 and then print the collatz series for 25.

You can then run a loop around that function calling it with parameter 24, 23, 22 etc. This will give the collatz series for all those numbers.

I am not giving the code, as you should try it out for yourself.

You should add an extra loop to iterate from x down to 1 .

Note that your code does not work correctly for the value 1 and does not count the number of outputs at the right spot, leading to a surprising + 2 final adjustment.

Moving the code to a separate function would improve readability.

Your guard loop does not make sense: stopping after x * x iterations assumes x * x is in the range of unsigned long , which can be very low ( x < 65536 on Windows). larger values might give an incorrect result. Just removing the guard test simplifies the code and if we assume the Collatz conjecture to be true (It has been tested for all starting values up to 2 60 ) any counter examples yielding an infinite loop would be welcome.

Here is a simplified and extended version:

#include <stdio.h>

int main(void) {
    unsigned long xx, x, a;

    printf("Enter the value of X: ");
    if (scanf("%lu", &xx) != 1)
        return 1;

    for (; xx >= 1; xx--) {
        x = xx;
        a = 0;
        for (;;) {
            printf("%lu ", x);
            a++;
            if (x == 1)
                break;
            if (x % 2 == 0) {
                x = x / 2;
            } else {
                x = (3 * x) + 1;
            }
        }
        printf("= %lu\n", a);
    }
    return 0;
}

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