The number 1089 is the smallest one, non palindromic, that has the same prime factors >that its reversal. Thus,
prime factorization of 1089 with 3, 3, 11, 11 -------> 3, 11
prime factorization of 9801 with 3, 3, 3, 3, 11, 11 -------> 3, 11The task for this kata is to create a function same_factRev(), that receives a nMax, to >find all the numbers with the above property, bellow nMax.
the function same_factRev(), will output a sorted list with the found numbers bellow >nMax
Let'se some cases
same_factRev(1100) -----> [1089]
same_factRev(2500) -----> [1089, 2178](Palindromic numbers are like: 171, 454, 4224, these ones should be discarded)
題目理解:設計一函式代入正整數nMax,若某數n與其位數顛倒後整數rev_i,兩者質因數分解後所含的質數種類皆相同。則收集所有小於nMax的正整數中符合此條件的數,以列表形式返還。
注意若n為回文數字,則不計入。
先設法找到某數number的最小因數(同時也會是最小質因數),可參考Day4內說明。
def first_divisor(num):
"""找到正整數num的1以外最小因數並返還"""
for n in range(2,int(num**0.5+1)):
if num % n == 0:
return n
#若在根號num範圍內無法找到因數,代表num本身為質數並返還num
return num
接著利用number會等於其全部質因數相乘的特性,反覆將number除以其最小質因數的結果再拿去找最小值因數,即可完成number的質因數分解。
def prime_find(number):
"""找到正整數number所有的質因數"""
num = number
prime_divisor = []
while first_divisor(num) != num:
#將找到的最小因數加入prime_divisor並將num除去最小因數
#因為number為所有的prime_divisor相乘,故將num不斷除去找到到質因數直到num為止
prime_divisor.append(first_divisor(num))
num = num/first_divisor(num)
#則此時num為number的最後一個質因數
prime_divisor.append(int(num))
return prime_divisor
最後再利用前面的兩個小函式,來找最終題目所需,如下:
def same_factRev(nMax):
"""找到某數i與其顛倒後數字rev_i兩者具有相同質因數種類""""
reslut = []
for i in range(1,nMax):
#建立空字串將加入str(i)倒轉後的結果,即可得到數字i的reversal後數字rev_i
rev_i = int("".join(reversed(str(i))))
#檢查set()後的i與rev_i是否相等且不為空,且應題目要求不計回文數字故i不可與rev_i相同
if set(prime_find(i)) == set(prime_find(rev_i)) != set() and rev_i != i:
#皆符合則將i加入reslut
reslut.append(i)
return reslut