一个数的唯一素因数乘积的Python程序
给定一个数 n,我们需要找到它所有唯一素因子的乘积。质因数:它基本上是质数本身的一个数的因数。
例子:
Input: num = 10
Output: Product is 10
Explanation:
Here, the input number is 10 having only 2 prime factors and they are 5 and 2.
And hence their product is 10.
Input : num = 25
Output: Product is 5
Explanation:
Here, for the input to be 25 we have only one unique prime factor i.e 5.
And hence the required product is 5.
方法1(简单)
使用从 i = 2 到 n 的循环并检查 i 是否是 n 的因数,然后检查 i 是否是素数本身,如果是,则将产品存储在产品变量中并继续此过程直到 i = n。
# Python program to find sum of given
# series.
def productPrimeFactors(n):
product = 1
for i in range(2, n+1):
if (n % i == 0):
isPrime = 1
for j in range(2, int(i/2 + 1)):
if (i % j == 0):
isPrime = 0
break
# condition if \'i\' is Prime number
# as well as factor of num
if (isPrime):
product = product * i
return product
# main()
n = 44
print (productPrimeFactors(n))
# Contributed by _omg
输出:
22
方法2(高效):
这个想法是基于高效程序来打印给定数字的所有素因子
# Python program to find product of
# unique prime factors of a number
import math
def productPrimeFactors(n):
product = 1
# Handle prime factor 2 explicitly so that
# can optimally handle other prime factors.
if (n % 2 == 0):
product *= 2
while (n%2 == 0):
n = n/2
# n must be odd at this point. So we can
# skip one element (Note i = i +2)
for i in range (3, int(math.sqrt(n)), 2):
# While i divides n, print i and
# divide n
if (n % i == 0):
product = product * i
while (n%i == 0):
n = n/i
# This condition is to handle the case when n
# is a prime number greater than 2
if (n > 2):
product = product * n
return product
# main()
n = 44
print (int(productPrimeFactors(n)))
# Contributed by _omg
输出:
22
更多详细信息,请参阅关于一个数的唯一素因数乘积的完整文章!