ezar hanna
ezar hanna

Reputation: 1

collatz conjecture, finding max number in sequence

hey guys i have to write a function that returns the max number in the collatz sequence(not the length), for example if n==7 the output should be 52 because its the largest number ;

int collatz_max(int n)
{
    int max=0;
        if(collatz_max(n)>max)
            {
           max=n;
            return max;
            }
        if(n%2==0)
        {
          return   collatz_max(n=n/2);
        }
        else
        
           return  collatz_max(n=n*3+1);
        }
}

Upvotes: 0

Views: 91

Answers (1)

Ed Heal
Ed Heal

Reputation: 60017

The statement

  if(collatz_max(n)>max)

Is just calling itself without changing n or doing anything else. So it would repeatedly just keep calling itself until it runs out of stack. You need to rethink the algorithm

Upvotes: 1

Related Questions