Saturday, 5 May 2012

UVa 100 The 3n + 1 problem Solution

#include<stdio.h>
int main()
{
int n,m,i,o,j,ans,sum;
while(scanf("%d%d",&n,&m)==2 && m>0 && n>0)
{
sum=0;
printf("%d %d ",n,m);
if(n>m)
{o=m;
m=n;
n=o;}
for(i=n;i<=m;i++)
    {
    ans=1;
    for(j=i;j!=1;j=j)
        {
        if(j%2==0)
        j=j/2;
        else
        j=3*j+1;
        ans=ans+1;
        }
    if(ans>=sum)
    sum=ans;
    }
printf("%d\n",sum);
}
return 0;
}

11 comments:

  1. brother can I share your blog link?
    I have a blog like u cupc71.blogspot.com please visit my blog and left your valuable comment about the blog

    ReplyDelete
    Replies
    1. yes, you can.
      wow, your blog is great resource for programmers. keep it up bro.... :)

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. #include

    int main()
    {
    int begin = 0;
    int end = 0;
    int contador = 1;
    int aux = 1;
    int aux2 = 1;
    int i = 0;

    while (scanf("%d %d",&begin,&end)==2 && begin > 0 && end > 0)
    {
    int numero = 0;
    int wrapper = 0;

    if(begin > end)
    {
    wrapper = end;
    end = begin;
    begin = wrapper;
    }


    for (i = begin; i <= end; i++)
    {

    numero = i;
    contador = 1;

    while (1)
    {
    if (numero == 1)
    break;

    if (numero % 2 == 0)
    {
    numero = numero / 2;
    }
    else
    {
    numero = 3 * numero + 1;
    }
    contador++;
    }

    aux2 = contador;

    if (i == begin)
    {
    aux = aux2;
    }
    else
    {
    if (aux <= aux2)
    {
    aux = aux2;
    }
    }
    }

    printf("%d %d ",begin,end);
    printf("%d\n",aux);

    }
    return 0;

    }

    ReplyDelete
  4. scanf("%d%d",&n,&m)==2 ,,why scanf ==2 ,,can u explain

    ReplyDelete
  5. bro , i am new in programming.. May I know what does the term "scanf("%d%d",&n,&m)==2" stands for? I mean u input two numbers ,that's why two? or else? please let me know.. Thank you :)

    ReplyDelete
    Replies
    1. scanf returns 1 for each value scanned by this function .

      so while(scanf("%d %d")==2) means your loop will keep looping as long as scanf returns 2 , if it gets no input it will return 0 , so loop will break.

      hope you understand .

      Delete
  6. https://murarisrinivasulu.wordpress.com/

    ReplyDelete
  7. if take 4 input at a time it shows wrong output, other hand than use scanf () by not using == 2 get the right output.... :)

    ReplyDelete
  8. if i use while(1) and put ifj=1 break. will it be correct?

    ReplyDelete
  9. can i use eof instead of using while()==2 ??

    ReplyDelete