[英]Given a number n, return true is all the factors of n are prime numbers. Note that 1 and the number itself are not considered as factors
public class AllFactorsArePrime {
public static void main(String[] args) {
AllFactorsArePrime obj = new AllFactorsArePrime();
boolean result = obj.areAllFactorsPrime(8);
System.out.println(result);
}
public boolean areAllFactorsPrime(int n) {
int j=0;
double k=n;
while(n%2==0){
n=n/2;
j=2;
}
for(int i=3; i<=n;i=i+2){
while(n%i==0){
n=n/i;
j=i;
}
}
if(j==0 ){
return 1;
}
return j;
}
above code return prime factors, but return should be true or false.any suggestion? 上面的代码返回了主要因素,但是返回应该是对还是错。有什么建议吗? Sample Input #1 样本输入#1
areAllFactorsPrime(22)
Sample Output #1 样本输出#1
true
Sample Input #2 样本输入2
areAllFactorsPrime(25)
Sample Output #2 样本输出2
true
Sample Input #3 样本输入#3
areAllFactorsPrime(32)
Sample Output #3 样本输出3
false
I think this is what you are trying to achieve! 我认为这就是您要实现的目标!
import java.util.*;
import java.lang.*;
import java.io.*;
public class AllFactorsArePrime {
public static void main(String[] args) {
AllFactorsArePrime obj = new AllFactorsArePrime();
boolean result = obj.areAllFactorsPrime(32);
System.out.println(result);
}
public boolean areAllFactorsPrime(int n) {
int count=0;
int j=0;
double k=n;
while(n%2==0){
n=n/2;
j=2;
count++;
}
for(int i=3; i<=n;i=i+2){
while(n%i==0){
n=n/i;
j=i;
count++;
}
}
if(count>=3)
{
return false;
}
else
return true;
}
}
The logic is pretty simple if you have more than 2 prime factors excluding 1 , that means you have atleast 1 composite factor which is prime1*prime2. 如果除1之外有2个以上素数,则逻辑很简单,这意味着您至少有1个复合素,即prime1 * prime2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.