Skip to content

Instantly share code, notes, and snippets.

@mkawserm
Created April 5, 2014 09:03
Show Gist options
  • Save mkawserm/9989369 to your computer and use it in GitHub Desktop.
Save mkawserm/9989369 to your computer and use it in GitHub Desktop.
The 3n + 1 problem
#!/usr/bin/env python
"""
Author : kawser
Author blog : http://blog.kawser.org
Problem ID : 100
Time Limit : 3s
OJ Link : http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36
"""
def swap(i,j):
return (j,i)
def main():
inp = raw_input()
#Total input argument is 2 and all are integers
i = int( inp.split(" ")[0]) #converting first input number into integer
j = int( inp.split(" ")[1]) #converting second input number into integer
#saving it into temporary variable
tempI = i
tempJ = j
if( i > j ): #we will check number from minimum to maximum
(i,j) = swap(i,j)
maxCycle = 0
Cycle = 0
while(i<=j):
n = i
Cycle = 1
while( n!=1 ):
if ( n%2!=0 ):
n = (3*n) + 1
else:
n = n/2
Cycle = Cycle + 1
if( Cycle > maxCycle ):
maxCycle = Cycle
i = i+1
print("%d %d %d"%(tempI,tempJ,maxCycle))
if __name__ == "__main__":
while(True):
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment