3n + 1算法

时间:2018-04-06 15:08:04

标签: c algorithm max collatz

给出了一些整数n。如果n为奇数,则执行3 n + 1的任务,如果n为偶数则执行n / 2。当n达到1时完成工作。在n达到1之前创建的数字称为循环长度。当两个数字I和j尝试获得I和j之间所有数字的最大循环长度。 有没有办法比较循环的长度而不写全局变量?

#include<stdio.h>
void cycle(int num) {
     int count = 1;
     while (1)
     {
            if (num == 1)
            break;

        if (num % 2 == 1) {
            num = 3 * num + 1;
            count++;
            printf("%d ", num);
        }
        else {
            num = num / 2;
            count++;
            printf("%d ", num);
        }
    }
    printf("\ncycle-length : %d\n", count);

}


void cycle_count(int num1,int num2) {
    int num;

    for (num = num1; num <= num2; num++) 
    {
        cycle(num);
    }

}
void main() 
{
    int num1, num2;
    scanf("%d %d", &num1,&num2);
    cycle_count(num1, num2);

    return;

}

1 个答案:

答案 0 :(得分:2)

只需将这些函数声明为返回找到的值即可。

考虑到根据C标准,没有参数的函数main应声明为

int main( void )

这是一个示范程序

#include <stdio.h>

size_t cycle( unsigned int num ) 
{
    size_t count = 0;

    enum { EVEN = 0, ODD };     

    while ( num > 1 )
    {
        switch ( num % 2 )
        {
            case EVEN:
                num /= 2;
                break;

            case ODD:
                num = 3 * num + 1;
                break;
        }

        ++count;
    }

    return count;
}

size_t cycle_count( unsigned int num1, unsigned int num2 ) 
{
    size_t max_count = 0;

    if ( num2 < num1 )
    {
        unsigned int tmp = num1;
        num1 = num2;
        num2 = tmp;
    }

    for ( unsigned int num = num1; num <= num2; num++ ) 
    {
        size_t n = cycle( num );
        if ( max_count < n ) max_count = n;
    }

    return max_count;
}

int main(void) 
{
    unsigned int num1, num2;

    printf( "Enter two non-negative numbers: " );
    scanf( "%u %u", &num1, &num2 );

    printf( "The maximum cycle length is equal to %zu\n", cycle_count( num1, num2 ) );

    return 0;
}

它的输出可能看起来像

Enter two non-negative numbers: 1 10
The maximum cycle length is equal to 19

注意在我的函数中,我开始计算从0开始的循环长度。如果需要,可以更改初始值。