Search code examples
pythonpython-2.7loopspython-itertools

find total number of divisors of number, for t test cases in python


i make a programe to find the number of divisor for a number with test case to submit it on the online judge so i write the code like that

num_case=int(raw_input())
num=list()
final_o=[]
for x in xrange(num_case):
     num.append(int(raw_input()))
for h in num:
     result=[int(h)]
for i in xrange(1, h + 1):
    if h % i == 0:
        result.append(i)
a=final_o.append(len(result)-1)
for ff in final_o:
     print ff

in this case i make user input the number of test case for example 3 and then enter the number for example 12 7 and 36 then he get the output like this 6 2 9 that the 12 have 6 divisor number and so on this code work well but i get Memory Error when i submit it so i try to use itertools because range in for loop is small and xrange take a lot of time more than 2 second but i dont get any output code

from itertools import count
num_case=int(raw_input())
num=list()
final_o=[]
for x in xrange(num_case):
     num.append(int(raw_input()))
for h in num:
    result=[int(h)]
    n=int(raw_input())
for i in count(1):
    if n % i == 0:
        result.append(i)
    elif count==n+1:
        break
a=final_o.append(len(result)-1)
for ff in final_o:
   print ff

any one have a solution to this bug ? Note that the time for the test case 2 second and the range of the numbers is 10^9 and test case 100 How i Do that ?


Solution

  • def devisors_number(n):
        result = 0
        sqrt_n = int(n**0.5)
    
        for i in xrange(1, sqrt_n + 1):
            if n % i == 0:
                result += 1
    
        result *= 2
    
        if sqrt_n**2 == n:
            result -= 1
    
        return result
    
    
    n = int(raw_input("Enter a number: "))
    d = devisors_number(n)
    print "{0} has {1} devisors".format(n, d)