Я уверен, что кто-то еще придумает хороший ответ, связанный с арифметикой модуля. Вот наивный подход...
Каждый из факторов может быть сам по себе факторизован (хотя это может быть дорогостоящей операцией).
Учитывая факторы, вы можете искать группы повторяющихся факторов.
Например, используя ваш пример:
Простые множители 9: 3, 3
Простые множители 6: 2, 3
Все простые множители: 2, 3, 3, 3
Есть две тройки, поэтому у вас есть ответ (квадрат 3 делит 54).
Второй пример 36 х 9 = 324
Простые множители числа 36: 2, 2, 3, 3
Простые множители 9: 3, 3
Все простые множители: 2, 2, 3, 3, 3, 3
Итак, у вас есть две двойки и четыре тройки, что означает повторение 2x3x3. 2x3x3 = 18, значит, квадрат 18 делит 324.
Изменить: прототип Python
import math
def factors(num, dict):
""" This finds the factors of a number recursively.
It is not the most efficient algorithm, and I
have not tested it a lot. You should probably
use another one. dict is a dictionary which looks
like {factor: occurrences, factor: occurrences, ...}
It must contain at least {2: 0} but need not have
any other pre-populated elements. Factors will be added
to this dictionary as they are found.
"""
while (num % 2 == 0):
num /= 2
dict[2] += 1
i = 3
found = False
while (not found and (i <= int(math.sqrt(num)))):
if (num % i == 0):
found = True
factors(i, dict)
factors(num / i, dict)
else:
i += 2
if (not found):
if (num in dict.keys()):
dict[num] += 1
else:
dict[num] = 1
return 0
#MAIN ROUTINE IS HERE
n1 = 37 # first number (6 in your example)
n2 = 41 # second number (9 in your example)
dict = {2: 0} # initialise factors (start with "no factors of 2")
factors(n1, dict) # find the factors of f1 and add them to the list
factors(n2, dict) # find the factors of f2 and add them to the list
sqfac = 1
# now find all factors repeated twice and multiply them together
for k in dict.keys():
dict[k] /= 2
sqfac *= k ** dict[k]
# here is the result
print(sqfac)
person
Tony
schedule
20.12.2014