Home > front end >  Write as function to find the NUMBER of factors in an integer? (not listing the factors itself)
Write as function to find the NUMBER of factors in an integer? (not listing the factors itself)

Time:06-06

Write a function that returns the number of positive factors of an integer, including 1 and the number itself. (Y is a factor of X if Y divides evenly into X, i.e. if X modulus Y is 0.) For example: 6 returns 4 (factors are 1, 2, 3 and 6) 12 returns 6 (factors are 1, 2, 3, 4, 6 and 12) [execution time limit] 4 seconds (py3) [input] integer number The target number [output] integer The number of factors

I have the code that lists the factors of an integer but not how many factors there are in the integer.

def solution(n):
    result = []
 
    for i in range(1, n   1):
        if n % i == 0:
            result.append(i)
            
    return result

CodePudding user response:

In order to count the amount of factors, you should use a counter variable that would be incremented every time you find a factor of the number. So instead of declaring a list and append the factors to the list, you should declare a new Integer variable and initialize it with the value 0:

counter = 0

From now on, every time you find a number which is the factor of the given number, we will just increment this counter variable and just like that the program will count the amount of factors.

def solution(n):
    # result = []
    counter = 0
    for i in range(1, n   1):
        if n % i == 0:
            # result.append(i)
            counter  = 1
    
    return counter

CodePudding user response:

Some improvements could be made by only finding the factors smaller than the square root. If n is divisible by a, it is also divisible by n/a. If n is a perfect square, add 1 to the count (instead of 2). This already saves 90 iterations for n = 100.

from math Import sqrt, ceil
def solution(n):
    count = 0
    for i in range(1, ceil(sqrt(n))):
        if n % i == 0:
            count  = 2
    if sqrt(n) == int(sqrt(n)):
      count  = 1
    return count
  • Related