iT邦幫忙

2022 iThome 鐵人賽

DAY 20
0
自我挑戰組

Udemy課程上完你也可以開始Codewars 30天系列 第 20

[Day20] Codewars >>> Integers: Recreation One (Python)

  • 分享至 

  • xImage
  •  

題目(5kyu):

1, 246, 2, 123, 3, 82, 6, 41 are the divisors of number 246. Squaring these divisors we >get: 1, 60516, 4, 15129, 9, 6724, 36, 1681. The sum of these squares is 84100 which is >290 * 290.

Task
Find all integers between m and n (m and n integers with 1 <= m <= n) such that the sum >of their squared divisors is itself a square.

We will return an array of subarrays or of tuples (in C an array of Pair) or a string. >The subarrays (or tuples or Pairs) will have two elements: first the number the squared >divisors of which is a square and then the sum of the squared divisors.

Example:
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 "Sample Tests".

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.

解題思路

題目理解:給定一個範圍m~n,範圍中的整數若其所有因數的平方之和,恰為某整數的平方,則回傳此數以及此數所有因數的平方和。
此題可以參考Day4中判斷質數的類似方法來查找某數的因數,應用如下:

import math

def list_squared(m, n):
    """找到範圍中的整數其所有因數平方和,其和恰為某整數的平方"""
    result = []
    for num in range(m, n + 1):
        #因數成對存在故希望一次將成對因數皆收集,但若此因數恰為num的平方根會有重複收集問題,故用set()排除
        divisors = set()
        #找出num所有的因數,確認是否為因數時可以找到該數的平方根為止
        for i in range(1, int(math.sqrt(num)+1)):
            if num % i == 0:
                divisors.add(i**2)
                #因數成對存在,故找到因數後(num/i)會是其另一個因數
                divisors.add(int(num/i)**2)
        all_sum = sum(divisors) 
        sr = math.sqrt(all_sum) 
        #若sr為整數則符合題目要求,故若sr往最下取整去除小數後仍與自己相等,代表sr本身為整數
        if sr == math.floor(sr) :
            result.append([num, all_sum])
    return result

上一篇
[Day19] Codewars >>> Calculating with Functions (Python)
下一篇
[Day21] Codewars >>> Luck check (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言