C 查找具有一定步数/计数的最小起始值的数字

C 查找具有一定步数/计数的最小起始值的数字,c,optimization,collatz,C,Optimization,Collatz,我正在做一个Collatz猜想程序。我有一个遵循简单规则的序列: 如果当前学期是偶数:下一学期是当前学期的一半 如果当前项为奇数:下一项为当前项的三倍,加1 我们继续这样做,直到我们达到一,并计算使用的每个术语 例如:对于数字17,我们有: 17522613402005168421 因此,计数为13 我特别需要帮助的是,我需要找到最小的起始值(数字),它的计数超过1234 即: 1有计数1 2有计数2 3等于8 4等于3 5等于6 6等于9 18等于21 97等于119 等

我正在做一个Collatz猜想程序。我有一个遵循简单规则的序列:

  • 如果当前学期是偶数:下一学期是当前学期的一半

  • 如果当前项为奇数:下一项为当前项的三倍,加1

我们继续这样做,直到我们达到一,并计算使用的每个术语

例如:对于数字17,我们有:

17522613402005168421

因此,计数为13

我特别需要帮助的是,我需要找到最小的起始值(数字),它的计数超过1234

即:

  • 1有计数1

  • 2有计数2

  • 3等于8

  • 4等于3

  • 5等于6

  • 6等于9

  • 18等于21

  • 97等于119

这是我拥有的代码,我认为它可以工作,但需要非常长的时间来处理。我如何优化它,以便更快地找到计数? 有人建议我进行二进制搜索,但计数不是线性的,因此不起作用

#include <stdio.h>

int main (void) {


    unsigned long long int num1 = 1;
    while (num1 <= 99999999999999999) {   

    unsigned long long int num = num1;
    int count = 1;
    while (num != 1) {

        if (num % 2 == 0) {
            num = (num/2);
            count++;
        }

        else {
            num = ((num*3) + 1);   
            count++;
        }

    }

    if (count > 1234) {
        printf("%llu\n", num1);
        break;
    }

    num1++;
    }

    return 0;
}
#包括
内部主(空){
无符号长整型num1=1;
而(num1 1234){
printf(“%llu\n”,num1);
打破
}
num1++;
}
返回0;
}

当您找到从任何特定值开始的序列长度时,您还可以找到从沿途看到的每个数字开始的序列长度。你应该记住你看到的所有数字的长度小于,比如1000000,这样你下次看到它们时就可以停止跟踪了。

当你找到从任何特定值开始的序列长度时,你也可以找到从你看到的每个数字开始的序列长度。你应该记住你看到的所有数字的长度,比如说,小于1000000,这样你下次看到它们时就可以停止跟踪了。

你怎么知道长度为1234的序列不会上升到与long-long不匹配的值

你可能不知道。因此,您需要一个bignum实现


有一个特别干净的bignum Collatz检查器实现(schweikhardt的条目,嗯)。您可以将此作为起点。

如何知道长度为1234的序列不会上升到不适合长序列的值

你可能不知道。因此,您需要一个bignum实现


有一个特别干净的bignum Collatz检查器实现(schweikhardt的条目,嗯)。您可以将此作为起点。

产生超过1234步的Collatz序列的最小根是133561134663。它达到最大值319497287463520,这是一个49位的值。因此,许多C库可以使用
(通常通过
)中提供的
uint64\t
对该序列进行评估

不幸的是,有许多序列的起点较低,需要高达71位的整数才能正确解析,比如始于110243094271的573步序列

最烦人的是,如果您使用64位无符号整数实现Collatz序列,而不检查溢出,那么您将为这些序列计算错误的长度;但是因为它们恰好有令人不感兴趣的长度,所以bug被屏蔽了,您仍然可以找到前面提到的解决方案

从本质上讲,如果这是一个C练习,那么它就是一个错误:即使是一个可怕的错误和有限的实现也能找到正确的答案


我碰巧在64位Linux上使用了GCC-5.4.0(在笔记本电脑上的核心i5-7200U CPU上运行),因此我可以对Collatz序列使用
unsigned\uu int128
,一种128位无符号整数类型。我还有16个GiB的RAM,其中我使用了大约12个GiB,用于存储序列长度高达130亿(13×109)的奇数索引

当你发现序列的长度从奇数i开始时,从2i开始的序列的长度就要长一步(但在其他方面是相同的)。事实上,有一个从2ki开始的序列,正好比k步长。如果您只寻找某个最小长度序列的最小起始值,则可以忽略所有偶数起始点,直到k足够小(基本上括起需要查看的起始值范围)

即使只考虑起始值也会带来显著的加速(20%或更高),但我在这里画了我的“线”,而是检查每个起始值

为了加快计算速度,我使用了内置的uuu builtin_ctz()GCC(64位的无符号长)来查找连续最低有效零位的数量。这样我可以一次性处理所有连续的“偶数”步骤,但正确计算步骤数

我还将序列步进器分为两个并行步进器,一个处理状态适合64位变量的情况,另一个处理需要完整128位的情况

在仅64位的部分中,如果当前状态的序列长度是可缓存的,我将查找它。如果它不是零,我把它加到我们已经完成的步骤数上,我得到了结果。否则,我会将缓存条目索引和从根开始的步骤数添加到一个小的更新缓存中。这样,当我得到结果时,我不需要重复序列,只需在一个紧密的循环中应用更新。在乘以3并加1之前,我会检查值是否溢出(6148914691236517205溢出,到264);如果是的话,我切换到128位部分,然后在那里进行乘法和运算

在128位部分,我假设我们没有那么多内存(在exabyte范围内),所以我根本不需要担心缓存部分。在我乘三加一之前
#define  _POSIX_C_SOURCE  200809L
#define  _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <inttypes.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>

#define  MAX_SEQ_LEN  2000

#define  OVER64       UINT64_C(6148914691236517205)

typedef  unsigned __int128   u128;
typedef  uint64_t            u64;

static inline u64  u128_lo(const u128  u) { return (u64)u;         }
static inline u64  u128_hi(const u128  u) { return (u64)(u >> 64); }

static inline u64 highest_bit_set_64(const u64  u)
{
    if (sizeof u == sizeof (unsigned int))
        return 63 - __builtin_clz(u);
    else
    if (sizeof u == sizeof (unsigned long))
        return 63 - __builtin_clzl(u);
    else
    if (sizeof u == sizeof (unsigned long long))
        return 63 - __builtin_clzll(u);
    else
        exit(EXIT_FAILURE);
}

static unsigned int highest_bit_set_128(u128 u)
{
    u64  hi = u128_hi(u);
    if (hi)
        return 64 + highest_bit_set_64(hi);
    else
        return highest_bit_set_64(u128_lo(u));
}

static inline unsigned int  ctz64(const u64  u)
{
    if (sizeof u <= sizeof (unsigned int))
        return __builtin_ctz(u);
    else
    if (sizeof u <= sizeof (unsigned long))
        return __builtin_ctzl(u);
    else
    if (sizeof u <= sizeof (unsigned long long))
        return __builtin_ctzll(u);
    else
        exit(EXIT_FAILURE);
}

static inline unsigned int  ctz128(const u128  u)
{
    if (sizeof u == sizeof (unsigned long long))
        return __builtin_ctzll(u);
    else {
        const u64  lo = u128_lo(u);
        if (lo)
            return ctz64(u);
        else
            return 64 + ctz64(u128_hi(u));
    }
}

static const char *s128(u128 u)
{
    static char  buffer[40];
    char        *p = buffer + sizeof buffer;

    *(--p) = '\0';
    do {
        *(--p) = '0' + (u % 10);
        u /= 10;
    } while (u);

    return p;
}

static struct timespec  wall_started, wall_now;
static inline void      wall_start(void)
{
    clock_gettime(CLOCK_MONOTONIC, &wall_started);
}
static inline double    wall_seconds(void)
{
    clock_gettime(CLOCK_MONOTONIC, &wall_now);
    return (double)(wall_now.tv_sec - wall_started.tv_sec)
         + (double)(wall_now.tv_nsec - wall_started.tv_nsec) / 1000000000.0;
}

static struct timespec  cpu_elapsed;
static inline double    cpu_seconds(void)
{
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &cpu_elapsed);
    return (double)cpu_elapsed.tv_sec + (double)cpu_elapsed.tv_nsec / 1000000000.0;
}

static int out_and_err = 0;
static void print(const char *fmt, ...)
{
    va_list  args;

    va_start(args, fmt);
    vdprintf(STDOUT_FILENO, fmt, args);
    va_end(args);

    if (out_and_err) {
        va_start(args, fmt);
        vdprintf(STDERR_FILENO, fmt, args);
        va_end(args);
    }
}

static size_t        cache_index[MAX_SEQ_LEN];
static unsigned int  cache_depth[MAX_SEQ_LEN];

static u64           seq_max = 0;  /* 2*seq_num */
static size_t        seq_num = 0;
static uint16_t     *seq_len = NULL;

static unsigned int  tip_bits = 0;
static u128          tip_max  = 0;

static inline unsigned int  collatz_length(const u64 root, u128 *maxto)
{
    u128          curr128, max128;
    u64           curr64, max64, lo;
    size_t        cached = 0, i;
    unsigned int  steps = 1, n;

    curr128 = max128 = root;
    curr64 = max64 = root;

any64bit:

    if (!(curr64 & 1)) {
        n = ctz64(curr64);
        curr64 >>= n;
        steps += n;
    }

    if (curr64 >= OVER64) {
        curr128 = curr64;
        goto odd128bit;
    }

odd64bit:

    if (curr64 <= 1)
        goto done;

    if (curr64 < seq_max) {
        i = curr64 >> 1;
        if (seq_len[i]) {
            steps += seq_len[i];
            goto done;
        }

        cache_index[cached] = i;
        cache_depth[cached] = steps;
        cached++;
    }

    curr64 += curr64 + curr64 + 1;
    steps++;

    if (max64 < curr64)
        max64 = curr64;

    goto any64bit;


any128bit:

    if (!(curr128 & 1)) {
        n = ctz128(curr128);
        curr128 >>= n;
        steps += n;

        if (!u128_hi(curr128)) {
            lo = u128_lo(curr128);
            if (lo <= 1)
                goto done;
            if (lo < OVER64) {
                curr64 = lo;
                goto odd64bit;
            }
        }
    }

odd128bit:

    if (u128_hi(curr128) >= OVER64) {
        print("Overflow at root %" PRIu64 ".\n", root);
        exit(EXIT_FAILURE);
    }

    curr128 += curr128 + curr128 + 1;
    steps++;

    if (max128 < curr128)
        max128 = curr128;

    goto any128bit;

done:

    if (cached >= MAX_SEQ_LEN) {
        print("Update cache overrun.\n");
        exit(EXIT_FAILURE);
    }

    while (cached-->0)
        seq_len[ cache_index[cached] ] = steps - cache_depth[cached];

    if (max128 < (u128)max64)
        max128 = max64;

    if (maxto)
        *maxto = max128;

    if (tip_max <= max128) {
        const unsigned int  maxbits = highest_bit_set_128(max128) + 1;
        tip_max = max128;
        if (tip_bits <= maxbits) {
            tip_bits = maxbits;
            print("%" PRIu64 " length %u (reaches %s - %u bits).\n", root, steps, s128(max128), maxbits);
        }
    }

    return steps;
}

int main(void)
{
    unsigned int  n, nmax = 0;
    u128          m;
    uint64_t      i = 1;

    wall_start();

    /* If standard output is redirected to a file, print everything to standard error also. */
    out_and_err = (isatty(STDERR_FILENO) && !isatty(STDOUT_FILENO));

    /* Try allocating up to 16 GiB of cache. */
    seq_num = (size_t)1024 * 1024 * 1024 * 16 / sizeof seq_len[0];
    while (1) {
        seq_len = malloc(seq_num * sizeof seq_len[0]);
        if (seq_len)
            break;
        seq_num = ( seq_num * 7 ) / 8;
    }
    seq_max = 2 * (uint64_t)seq_num;
    memset(seq_len,~0, seq_num * sizeof seq_len[0]);
    memset(seq_len, 0, seq_num * sizeof seq_len[0]);

    print("Allocated %zu entries (%.3f GiB)\n", seq_num, (double)(seq_num * sizeof seq_len[0]) / 1073741824.0);

    do {
        n = collatz_length(i, &m);
        if (n >= nmax) {
            const double cs = cpu_seconds();
            const double ws = wall_seconds();
            const char  *s = s128(m);
            nmax = n;
            print("%" PRIu64 " length %u (reaches %s) [%.3f seconds elapsed, %.3f seconds CPU time]\n", i, n, s, ws, cs);
        }

        i++;
    } while (nmax < MAX_SEQ_LEN);

    return EXIT_SUCCESS;
}