In the algorithm to obtain the mineral water,

Asked 2 years ago, Updated 2 years ago, 14 views

def count_factors(num):
    loop=num**0.5
    # # for square number
    if loop==int(loop):
        count=1
    else:
        count=0
    i=1
    while i<loop:
        if num%i==0:
            count+=2
        i+=1
    return count

Why do we count +2 in the function of finding the mineral water? I think I'm doing +2 with a root I don't quite understand.

python

2022-09-20 20:47

1 Answers

A function to obtain the number of abbreviations for a given number.

if loop == int(loop):
    count = 1
else:
    count = 0

In this part, if the square root of num is an integer, that is, if num is a square number, count starts from 1, and if not, count starts from 0. If num is a square number, it has the square root as an abbreviation, so that's where you count it.

i = 1
while i < loop:
    if num % i == 0:
        count += 2
    i += 1

This is the part from 1 where you count how many abbreviations there are in a number less than a given number of square roots and add them to the count by twice that number. If there is one mineral water, there will be another matching mineral water, so add 2 to the count.

For example, if num comes in with 10, the square root of 3.16 ... in a range less than the square root of 3.16 ... there will be a factor of 1 and 2, and there will be a pair of 10 and 5 in a range greater than the square root.


2022-09-20 20:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.