Java程序求乘积的唯一素数因子

给定一个数n,我们需要找到它所有唯一素因子的乘积。 主要因素: 它基本上是一个数的因子,这个数本身就是一个素数。

null

例如:

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。

// Java program to find product of
// unique prime factors of a number.
public class GFG {
public static long productPrimeFactors( int n)
{
long product = 1 ;
for ( int i = 2 ; i <= n; i++) {
// Checking if 'i' is factor of num
if (n % i == 0 ) {
// Checking if 'i' is a Prime number
boolean isPrime = true ;
for ( int j = 2 ; j <= i / 2 ; j++) {
if (i % j == 0 ) {
isPrime = false ;
break ;
}
}
// condition if 'i' is Prime number
// as well as factor of num
if (isPrime) {
product = product * i;
}
}
}
return product;
}
public static void main(String[] args)
{
int n = 44 ;
System.out.print(productPrimeFactors(n));
}
}
// Contributed by _omg


输出:

22

方法2(高效) 这个想法是基于 打印给定数的所有素数因子的高效程序

// Java program to find product of
// unique prime factors of a number.
import java.util.*;
import java.lang.*;
public class GFG {
public static long productPrimeFactors( int n)
{
long 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 ( int i = 3 ; i <= Math.sqrt(n); i = i + 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;
}
public static void main(String[] args)
{
int n = 44 ;
System.out.print(productPrimeFactors(n));
}
}
// Contributed by _omg


输出:

22

请参阅完整的文章 数的唯一素因子的乘积 更多细节!

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享