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

时间:2018-08-17 03:45:07

标签: c optimization collatz

我正在研究Collat​​z猜想程序。我遵循以下简单规则:

  • 如果当前项是偶数:下一项是当前项的一半。

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

我们继续进行此操作,直到达到一个并计算每个使用的术语。

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

17 52 26 13 40 20 10 5 16 8 4 2 1

因此,计数为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;
}

3 个答案:

答案 0 :(得分:2)

产生Collat​​z序列比1234步长的序列的最小根为133561134663。最大根为319497287463520,它是49位值。因此,可以使用许多C库使用uint64_t中提供的<stdint.h>(通常通过<inttypes.h>来评估此序列)。

不幸的是,有很多序列以较低的开头,需要最多71位整数才能正确解析,例如从110243094271开始的573步序列。

最令人讨厌的是,如果使用64位无符号整数实现Collat​​z序列,而不检查溢出,则会为这些序列计算错误的长度;但是由于它们的长度恰好没有意思,因此该错误被掩盖了,您仍然可以找到上述解决方案!

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


我碰巧在64位Linux上使用GCC-5.4.0(在笔记本电脑上的Core i5-7200U CPU上运行),因此我可以使用unsigned __int128(128位无符号整数类型)用于Collat​​z序列。我还拥有16 GiB的RAM,其中大约12 GiB的内存用于存储奇数索引的序列长度,最高可达130亿(13×10 9 )。

每当您发现以某个奇数 i 开始的序列长度时,以2 i 开始的序列长度就会长一个步骤(但其他方面相同) 。实际上,有一个序列从2 k i 开始,正好长了 k 个步骤。如果您只为某个最小长度的序列寻找最小的起始值,则可以忽略所有偶数起始点,直到 k 足够小(基本上将起始值的范围括起来,您需要研究一下)。

即使仅考虑起始值也可以显着提高速度(20%或更多),但是我在这里画了一条“线”,而是检查了每个起始值。

为加快计算速度,我使用了内置的__builtin_ctz()GCC(对于64位__builtin_ctzll()使用unsigned long long)来查找连续的最低有效零位的数量。这样,我可以一次性处理所有连续的“偶数”步骤,但是可以正确计算步骤数。

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

在仅64位的部分中,如果当前状态的序列长度是可缓存的,则将其查找。如果它不为零,则将其添加到已经完成的步骤数中,并得到结果。否则,我将该高速缓存条目索引以及从根开始的步骤数添加到较小的更新高速缓存中。这样,当我得到结果时,无需重复序列,而只需在紧缩循环中应用更新即可。在乘以三并加一之前,我要检查该值是否没有溢出(6148914691236517205溢出到2 64 );如果是这样,我切换到128位部分,并在那儿进行乘法加法运算。

在128位部分中,我假设我们没有足够的内存(在EB级),因此我完全不需要担心缓存部分。在确定乘以3(加curr128 += curr128 + curr128 + 1之前)之前,我确实检查状态是否不会溢出。

在使用单核的装有Intel Core i5-7200U的笔记本电脑上,计算从1到133561134663的所有Collat​​z序列的长度大约需要花费4253秒(约一个小时又十分钟)的CPU时间。

下一个更长的序列从158294678119开始,长度为1243步;为了达到这个目标,我的笔记本电脑消耗了一个半小时的CPU时间。

但是,到那时为止,代码已变得不像OP那样,而且太可怕了。特别是,要混合使用64位/ 128位循环,我不得不求助于goto。并且整个实现过程都被GCC内置函数所取代。我认为它几乎是只写代码的;也就是说,如果我怀疑它的任何部分,我将从头开始重写它。这是优化优先于可维护性和鲁棒性时的典型最终结果。

无论如何,要让其他人在x86-64上的Linux上使用GCC的人验证以上内容,这是可怕的代码 collat​​z.c

#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;
}

我使用gcc -Wall -O2 collatz.c -lrt -o collatz && ./collatz > results.txt进行编译和运行。 (优化可确保例如sizeof if子句在编译时得到解决,并使用条件移动来产生最少数量的缓慢条件跳转。因此,上述程序被设计设计为至少使用-O2编译。)它确实包含额外的代码,例如,显示所用的实时时间和CPU时间。由于它们与手头的问题无关,因此它们确实可以帮助TA轻松检测是否有人尝试将此代码作为自己的作业提交。

在运行的同时,我可以在另一个终端中使用grep -gk 3 results.txt来查看到目前为止获得的结果,并以增加的序列长度进行排序;或grep -gk 5 results.txt查看结果,该结果根据序列中的峰值(序列中的最大值)进行排序。

答案 1 :(得分:0)

当找到以任何特定值开头的序列的长度时,也会发现从沿途看到的每个数字开始的序列的长度。您应该记住所有看到的数字的长度(例如,小于1000000)的长度,以便下次看到它们时可以停止跟踪。

答案 2 :(得分:0)

您怎么知道长度为1234的序列不会上升为不适合很长的值?

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

有一个won the IOCCC的bignum Collat​​z检查器的特别干净的实现(schweikhardt的条目,哎呀)。您可以以此为起点。