-4
    from random import randrange

    a = randrange(1, 9)
    print (a)

    if (a % 2) == 0:         
        y = a / 2        
    while True:     
        if (y % 2) == 0:      
            y = y / 2
            print (y)
        else: 
            b = (a * 3) + 1
    while True: 
        if (b % 2) == 0:
            b = b / 2
        else: 
            b = (a * 3) + 1   
        print (b)

"I want to make a math problem solver in python that can find a random number

between 1 and 9. Then if it is odd so it multiply it with 3 and add 1 in it and if it

is even so it divide it by two and this process keep repeating. For example a number

computer choose is 7 so :
7*3 + 1 = 22
22/2 = 11
11*3 = 33
and so on.
It shouldn't stop until the answer is 0.Here is my code in which I tried but not sure where should I make it right?"

tlentali
  • 3,407
  • 2
  • 14
  • 21
Esbah
  • 9
  • 1
  • 5

3 Answers3

4

You have too many lines in there. You need to loop to stop repeating when the number becomes 1 (it will never become 0):

from random import randrange

a = randrange(1, 9)

while a != 1:
    print(a)
    if a % 2 == 0:
        a = a // 2
    else:
        a = (a * 3) + 1

print(a)
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

You can use the following code to check for any number or any range of numbers. This code is created by using the recursive function approach.

def f(x): #creating a function
  if x!=4:
    a.append(x)
    if x%2==0:
      while x%2==0:
        x=x/2
        a.append(x)
    x=3*x+1
    f(x)

For checking a particular value, run this:

a=[]
f(2**100+1) #2 to the power 10, plus 1
a[-1]

For checking for a range of values, run this:

for i in range(1,100):
  a=[]
  f(i)
  print(i, "gives output" ,a)
Shiv
  • 1
0

I call it impossible maths because never reaches zero, it just keeps on looping forever Collatz problem. But this function does that, it does not take any parameter.

import random as r

def impossible_math():
  x = r.ran(1,9)
  while x !=0:
   if x%2 ==0:
    x = x/2
    print(x)
   else:
    x = (x*3)+1
    print(x)

x = impossible_math()