From 93ea7fe5957b62f18e8fbd17a21696bd7de6332d Mon Sep 17 00:00:00 2001 From: mjfernez Date: Sun, 9 Feb 2020 15:16:26 -0500 Subject: Organized everything, update README --- 14-Longest-Collatz-Sequence/collatz.c | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 14-Longest-Collatz-Sequence/collatz.c (limited to '14-Longest-Collatz-Sequence/collatz.c') diff --git a/14-Longest-Collatz-Sequence/collatz.c b/14-Longest-Collatz-Sequence/collatz.c new file mode 100644 index 0000000..ec77af6 --- /dev/null +++ b/14-Longest-Collatz-Sequence/collatz.c @@ -0,0 +1,31 @@ +#include +#include +#include +// In C, it's immediately obvious my python solution is inefficient + +// For keeping track of the length of sequences +// c is a temporary counter, s changes when c reaches a new maximum +long int c = 0; +long int s = 0; +long int collatz(long int seed){ + c++; + if(seed == 1) + return 0; + if(seed % 2 == 0) + seed = seed / 2; + else + seed = 3 * seed + 1; + collatz(seed); +} + +int main(){ + for(long int i = 1; i < pow(10, 6); i++){ + c = 0; + collatz(i); + if(c > s){ + s = c; + } + } + printf("The longest sequence has %d numbers \n", s); + return 0; +} -- cgit v1.2.3