Sunday, February 25, 2018

C program : The Collatz function

The Collatz function is defined for a positive integer n as follows.
f(n) = 3n+1 if n is odd
        n/2     if n is even

We consider the repeated application of the Collatz function starting with a given integer n, as follows:
f(n), f(f(n)), f(f(f(n))), …

It is conjectured that no matter which positive integer n you start from, this sequence eventually will have 1 in it. It has been verified to hold for numbers up to 5 × 260

You will be given a positive number <= 32,000. You have to output how many times f has to be applied repeatedly in order to first reach 1.

 #include<stdio.h>
int main()
{

  int n,y=0,count=0;
  scanf("%d",&n);
  if(n==1)
  {printf("0");
  }
  else
  {
  while(y!=1)
  {
      if(n%2==0)
      {
        y=n/2;
        n=y;
      }
      else
      {
         y=3*n+1;
        n=y;
      }
    count++;
  }
  printf("%d",count);
  }
  return 0;
  }


Thanks
Happy Computing ! 

1 comment:

  1. #include
    int func(int n)
    { int a;
    if (n%2 == 0)
    {
    a=n/2;
    if(a!=1){
    printf("%d ",a);
    return (func(a));}
    else
    return (func(a));
    }
    else if (n == 1)
    {
    printf("%d",n);
    return 1;
    }
    else if (n%2 == 1 && n!=1)
    {
    printf("%d ",3*n+1);
    return (func(3*n + 1));
    }
    }
    int main()
    {
    int n;
    scanf("%d",&n);
    func(n);
    return 0;
    }

    ReplyDelete

Sacred Thought

28 April 2024 Today I am going to explain verse 31 - 38 chapter two for you all. There is no opportunity better than a righteous war (सत्य औ...