Optimization for finding perfect-square algorithm

后端 未结 3 1268
醉酒成梦
醉酒成梦 2020-12-21 18:04

The question I\'m working on is:

Find which sum of squared factors are a perfect square given a specific range. So if the range was (1..10) you woul

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-21 18:46

    The trick that frequently solves questions like this is to switch from trial division to a sieve. In Python (sorry):

    def list_squared(m, n):
        factor_squared_sum = {i: 0 for i in range(m, n + 1)}
        for factor in range(1, n + 1):
            i = n - n % factor  # greatest multiple of factor less than or equal to n
            while i >= m:
                factor_squared_sum[i] += factor ** 2
                i -= factor
        return {i for (i, fss) in factor_squared_sum.items() if isqrt(fss) ** 2 == fss}
    
    
    def isqrt(n):
        # from http://stackoverflow.com/a/15391420
        x = n
        y = (x + 1) // 2
        while y < x:
            x = y
            y = (x + n // x) // 2
        return x
    

    The next optimization is to step factor only to isqrt(n), adding the factor squares in pairs (e.g., 2 and i // 2).

提交回复
热议问题