From 664405be5f22ce10a92c63e7bc994becbe8d460a Mon Sep 17 00:00:00 2001 From: jombas Date: Tue, 22 Oct 2019 19:50:57 -0300 Subject: [PATCH] Added CollatzNumber algorithm --- CollatzNumber.c | 68 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 CollatzNumber.c diff --git a/CollatzNumber.c b/CollatzNumber.c new file mode 100644 index 0000000..239b58c --- /dev/null +++ b/CollatzNumber.c @@ -0,0 +1,68 @@ +/* +How this sequence works ?? +Basically, it pick a number and than check if this number is +even or odd. +If the number is even then we divide it by 2, +if it's odd just multiply by 3 and add 1 more. +After a while the sequence becomes continuous in 1, +this is why ... +And of course only numbers > 0 will work. + +Some INPUT/OUTPUT example: +-Imput: Contain the number to make the Collatz Sequence of it + +-Output: Contain a single line output that contains all the Collatz sequence + +TESTCASE: +Enter a number to calcule collatz: 34 +The collatz sequence is: 34 17 52 26 13 40 20 10 5 16 8 4 2 1... +*/ + +#include + +int v[1000000]; +int i = 0; + +int makeCollatz(int n){ + if(n <= 0){ + return 0; + } + else if(n == 1){ + return 1; + } + else{ + v[i] = n; + i++; + if(n % 2 == 0){ + n /= 2; + } + else{ + n = 3 * n + 1; + } + } + return makeCollatz(n); +} + +int main(void){ + int number, aux; + + printf("Enter a number to calcule collatz: \n"); + scanf("%d", &number); + aux = makeCollatz(number); + if(aux == 0){ + printf("Error\n"); + } + else if(aux == 1){ + v[i] = 1; + i++; + } + + printf("The collatz sequence is: \n"); + printf("%d", v[0]); + for(int j = 1; j < i; j++){ + printf(" %d", v[j]); + } + printf("...\n"); + + return 0; +}