pythonfor-loopif-statementprime-factoring

divisor count with printing the maximum value


I am new to python and there is a problem with one of my practices that I cant figure out, would appriciate if you could help me.

practice asks me to find the divisors through each 20 inputs with most divisors(count) and print it along with the original number, now the problem is sometimes there is 2 numbers with the same maximum divisors counts (for example 594 and 570 have 16 divisor numbers) and here I have to print the bigger number.

example input :

639
883
777
946
843
889
951
789
550
677
708
633
605
878
538
812
570
608
594
619

Desired output :

594 16

my code :

`def divisor(x) :
    cnt = 0
    for i in range(1, x+1) :
        if x % i == 0 :
            cnt += 1
    return cnt

div_max = 0
div_val = 0

for j in range(20) :
    x = int(input())
    if divisor(x) > div_max :
        div_max = divisor(x)
        div_val = x
        if div_val < x and divisor(x) == div_max :
                div_val = x
                div_max = divisor(x)

print(div_val, div_max)

my output : 570 16

please just advise on my current code, what is the problem and how I can fix it, cheers


Solution

  • Fixed a few logic issues to make it work.

    First simplify by computing once divisor(x) and assign it to the div variable.

    Changed your condition if div_val < x and divisor(x) == div_max to if div >= div_max.

    And mainly retain the max value : div_val = max(div_val, x).

    def divisor(x):
        cnt = 0
        for i in range(1, x+1):
            if x % i == 0 :
                cnt += 1
        return cnt
    
    
    div_max = 0
    div_val = 0
    
    for j in range(20):
        x = int(input())
        div = divisor(x)
        if div >= div_max:
            div_val = max(div_val, x)
            div_max = div
    
    print(div_val, div_max)