Home > database >  finding divisor with condition with python using 'if' and 'while'
finding divisor with condition with python using 'if' and 'while'

Time:07-14

trying to find how many divisors in 120, and printing divisors

div_n = 1
count = 0
n = 120

    while div_n <= n:
        if n % div_n == 0:
            print(div_n)
            count  = 1
        div_n  = 1
    print('number of divisor that 120 is {}.'.format(count))

the output should be

    1
    2
    3
    4
    5
    6
    8
    10
    12
    15
    20
    24
    30
    40
    60
    120
number of divisor that 120 is 16

But the problem I'm trying to solve says the code is not meeting the requirements. If there is nothing wrong, or more information is needed let me know.

CodePudding user response:

You can use this:

def get_factors(n):
    ret = []
    for i in range(1, n 1):
        if not n % i:
            ret.append(i)
    return ret

factors = get_factors(120)
print(*factors, sep='\n')
print('Total factors:', len(factors))

Output:

1
2
3
4
5
6
8
10
12
15
20
24
30
40
60
120
Total factors: 16

CodePudding user response:

Your code, once properly indented, works just fine. So I suspect the requirement you don't meet is that of speed - try the code with n=120000000.

When you look for divisors you don't need to check all the numbers from 1 to n: just check numbers from 1 to int(sqrt(n)) - when you find a divisor lower than the square root you have also found a related divisor, greater than the square root. In your example, when you find 2 you also find 60, and so on.

So I would do something like:

def divisors(n):
    divs = []
    divs2 = []
    r = int(sqrt(n))
    for d in range(1,r):
        q,m = divmod(n,d)
        if m == 0:
            divs.append(d)
            divs2.append(q)
    if n % r == 0:
        divs.append(r)
    for d in divs:
        print(d)
    for d in divs2[::-1]:
        print(d)
    print(f'Divisors for {n}: {len(divs) len(divs2)}')

EDIT: there was a small bug - if n happened to be a perfect square, my code would count its square root twice. So we better stop at int(sqrt(n))-1 and handle the square root separately.

  • Related