Codewars: Integers: Recreation One

一道5kyu。注意: api: is_integer() 可以替代我的方案


Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square!

Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number.

The result will be an array of arrays or of tuples (in C an array of Pair) or a string, each subarray having two elements, first the number whose squared divisors is a square and then the sum of the squared divisors.

Examples:

list_squared(1, 250) –> [[1, 1], [42, 2500], [246, 84100]]
list_squared(42, 250) –> [[42, 2500], [246, 84100]]
The form of the examples may change according to the language, see Example Tests: for more details.

Note

In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings.


import math
def factor_squared_sum(n):
    # could do some cache if time exceeded
    sum = 0
    nrt = int(math.sqrt(n))
    for i in range(1,nrt+1):
        # can be reduced to list deductive
        if not n%i:
            sum += i*i
            if int(n/i) != i:
                sum += int(n/i)**2 

    return sum
def list_squared(m, n):
    lst = list()
    for i in range(m,n+1):
        fss = factor_squared_sum(i)
        frt = int(math.sqrt(fss)*1000)
        if fss*1000000 == frt*frt: # Python supports infinite integers naturally
            lst.append([i,fss])
    return lst

猜你喜欢

转载自blog.csdn.net/qq_35279914/article/details/82190750
one