Search for all number optimization divisors

I wrote the following function, which finds all the divisors of a given natural number and returns them as a list:

def FindAllDivisors(x):
    divList = []
    y = 1
    while y <= math.sqrt(x):
        if x % y == 0:
            divList.append(y)
            divList.append(int(x / y))
        y += 1
    return divList

It works great with the exception that it is really slow when input contains an 18-digit number. Do you have any suggestions on how I can speed it up?

Update

I have the following primitiveness test method based on Fermat’s small theorem:

def CheckIfProbablyPrime(x):
    return (2 << x - 2) % x == 1

This method is really effective at checking a single number, however, I'm not sure if I should use it to compile all primes to a certain limit.

+3
source share
4 answers

. .

, :

def factorize(n, primes):
    factors = []
    for p in primes:
        if p*p > n: break
        i = 0
        while n % p == 0:
            n //= p
            i+=1
        if i > 0:
            factors.append((p, i));
    if n > 1: factors.append((n, 1))

    return factors

. . . .

:

def divisors(factors):
    div = [1]
    for (p, r) in factors:
        div = [d * p**e for d in div for e in range(r + 1)]
    return div

( ) . , .

+23

math.sqrt(x) , y . while, math.sqrt .

+3

, .

+1

, , , int . , Python 2.7, int x / int y int.

0

Source: https://habr.com/ru/post/1525676/


All Articles