Project Euler Question 14 (Collatz Problem)

后端 未结 8 1918
清酒与你
清酒与你 2020-11-27 07:58

The following iterative sequence is defined for the set of positive integers:

n ->n/2 (n is even) n ->3n + 1 (n is odd)

Using the rule above and starting wit

8条回答
  •  臣服心动
    2020-11-27 08:11

    I solved the problem some time ago and luckily still have my code. Do not read the code if you don't want a spoiler:

    #include 
    
    int lookup[1000000] = { 0 };
    
    unsigned int NextNumber(unsigned int value) {
      if ((value % 2) == 0) value >>= 1;
      else value = (value * 3) + 1;
      return value;
    }
    
    int main() {
      int i = 0;
      int chainlength = 0;
      int longest = 0;
      int longestchain = 0;
      unsigned int value = 0;
      for (i = 1; i < 1000000; ++i) {
        chainlength = 0;
        value = i;
        while (value != 1) {
          ++chainlength;
          value = NextNumber(value);
          if (value >= 1000000) continue;
          if (lookup[value] != 0) {
            chainlength += lookup[value];
            break;
          }
        }
    
        lookup[i] = chainlength;
    
        if (longestchain < chainlength) {
          longest = i;
          longestchain = chainlength;
        }
      }
      printf("\n%d: %d\n", longest, longestchain);
    }
    
    time ./a.out
    
    [don't be lazy, run it yourself]: [same here]
    
    real    0m0.106s
    user    0m0.094s
    sys     0m0.012s
    

提交回复
热议问题