mobzopi
mobzopi

Reputation: 131

Collatz algorithm in c

The next code displays the number of steps needed for a positive integer below 100 to get to the first 1 using the Collatz algorithm:

#include <stdio.h>
int main ()
{
    int i, num;
    int pasos;
    for(i=2;i<=100;i++){
        pasos=0;
        num=i;
        while(num!=1){
            if(num%2 == 0){
                num = num/2;
                pasos=pasos+1;
            }
            else
            {
                num = num*3 + 1;
                pasos=pasos+1;
            }
        }
        printf("\n");
        printf("El numero de pasos para llegar a 1 desde %i fueron: %i",i,pasos);
    }

I know that 97 is the number below 100 that needs the biggest number of steps(118) to get to the first 1, but how can I make the program display this biggest number instead of looking for it in the program output? I hope you understand, english is not my first language. Thanks!

Upvotes: 0

Views: 439

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84579

For example, as one approach to collecting the maximum number, you can simply add a ternary expression following your while loop:

#include <stdio.h>

int main () {
    int i=0, num=0;
    int pasos=0, maxpasos=0;;
    for (i = 2; i <= 100; i++) {
        pasos = 0;
        num = i;
        while (num != 1) {
            if (num % 2 == 0) {
                num = num / 2;
                pasos = pasos + 1;
            }

            else {
                num = num * 3 + 1;
                pasos = pasos + 1;
            }
        }
        maxpasos = (pasos > maxpasos) ? pasos : maxpasos;
        printf ("\n");
        printf ("El numero de pasos para llegar a 1 desde %i fueron: %i", i,
                pasos);
    }
    printf ("\n\nMaxpasos : %d\n\n", maxpasos);
    return 0;
}

output:

./bin/collatzmax

El numero de pasos para llegar a 1 desde 2 fueron: 1
El numero de pasos para llegar a 1 desde 3 fueron: 7
El numero de pasos para llegar a 1 desde 4 fueron: 2
(snip)
El numero de pasos para llegar a 1 desde 99 fueron: 25
El numero de pasos para llegar a 1 desde 100 fueron: 25

Maxpasos : 118

If you also need to store i when it occurs, simply add a variable int imax=0;, then when you store maxpaso, also store imax=i;. Example:

int i=0, num=0, imax=0;
...
    // maxpasos = (pasos > maxpasos) ? pasos : maxpasos;
    if (pasos > maxpasos) {
        maxpasos = pasos;
        imax = i;
    }

output:

Maxpasos (at 97): 118

Upvotes: 1

Related Questions