Advertisement
banovski

Project Euler, Problem #14, C

Dec 19th, 2022
1,091
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | Source Code | 0 0
  1. #include <stdio.h>
  2.  
  3. /* The following iterative sequence is defined for the set of positive
  4.  * integers: n → n/2 (n is even), n → 3n + 1 (n is odd). Using the
  5.  * rule above and starting with 13, we generate the following
  6.  * sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1. It can be
  7.  * seen that this sequence (starting at 13 and finishing at 1)
  8.  * contains 10 terms. Although it has not been proved yet (Collatz
  9.  * Problem), it is thought that all starting numbers finish at 1.
  10.  * Which starting number, under one million, produces the longest
  11.  * chain? NOTE: Once the chain starts the terms are allowed to go
  12.  * above one million. */
  13.  
  14. void solution_one(void);
  15.  
  16. int main()
  17. {
  18.      solution_one();
  19.      /* The number is 837799.
  20.       * real    0m1,664s
  21.       * user    0m1,642s
  22.       * sys 0m0,016s */
  23.  
  24.      return(0);
  25. }
  26.  
  27. void solution_one(void)
  28. {
  29.      int number;
  30.      long int item;
  31.      int sequence_length;
  32.      int current_max_sequence_length = 4;
  33.      int the_number = 1;
  34.  
  35.      for(number = 2; number < 1000000; number++)
  36.      {
  37.           item = number;
  38.           sequence_length = 2;
  39.  
  40.           while(item > 1)
  41.           {
  42.                if(item % 2 == 0)
  43.                     item /= 2;
  44.                else
  45.                     item = item * 3 + 1;
  46.  
  47.                sequence_length++;
  48.           }
  49.  
  50.           if(current_max_sequence_length < sequence_length)
  51.           {
  52.                current_max_sequence_length = sequence_length;
  53.                the_number = number;
  54.           }
  55.      }
  56.  
  57.      printf("The number is %d.\n", the_number);
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement