1 / 2
Dec 2005

i am tryin to solve the INUMBER problem using python but it goes into infinite loop ... wats my mistake ?

import sys
t=int(raw_input())
for i in range(0,t):
    n=int(raw_input())
    k=n
    flag=0
    i=1
    while flag!=1:
        ans=0
        n=n*i
        c=n
        while n>0:
            ans=ans+n%10
            n=n/10
        if ans==k:
            print c
            flag=1
    i=i+1
sys.exit(0)
    
  • created

    Dec '05
  • last reply

    Dec '05
  • 1

    reply

  • 184

    views

  • 2

    users

If I'm not wrong (if so - please correct me):
1) You are using variable i in a for loop

for i in range(0,t):

but in each pass you are resetting it to one:

i=1

2) After first pass of loop:

while n>0: 
  ans=ans+n%10 
  n=n/10

you are loosing value of n (after the loop it is equal to zero) - try to remember it in other variable, and restore it in next passes, otherwise in any next pass value of n is going to be zero, because you are setting it to:

n=n*i

3) I suppose that

i=i+1

should be indented, because now value of i is constant for all passes of the "flag" loop.
So the loop should look like this (I have changed i to j):

while flag!=1: 
  ans=0 
  n=n*j 
  c=n 
  while n>0: 
    ans=ans+n%10 
    n=n/10 
  if ans==k: 
    print c 
    flag=1 
  j=j+1