Thursday, March 17, 2011

694 - The Collatz Sequence


#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
long int cycle(long,long);
int main()
{
    long st,lm,n,c=0;
    cin>>st>>lm;
    while(st>0&&lm>0)
    {
        n=cycle(st,lm);
        printf("Case %ld: A = %ld, limit = %ld, number of terms = %ld\n",++c,st,lm,n);
        cin>>st>>lm;
    }
    exit(0);
}
long int cycle(long st,long lm)
{
    long int n=0;
    while(st<=lm&&st!=1)
    {
        if(!(st&1))
            st>>=1;
        else
            st=st*3+1;
        n++;
    }
    if(st==1)
        n++;
    return n;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.