我已经返回代码(用 Java)找到给定数字的最大质因数。
我发现检查了所有的因子,然后检查它是否是质数......如果是,打印最大的质因数。
import java.util.Scanner;
public class Problem3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int n = Integer.parseInt(sc.next()); // Takes input from the user.
int p=0,i,j,max=0,c=0;
for(i=1;i<n;i++) {
if(n%i != 0) { //Checks for factors and assigns that value to "c"
c = i;
for(j=1;j<c;j++) {
if(c%j==0) { //checks for prime number or not, if so... assign that value to "p"
p = j;
}
if(max<p) { // Checks for largest Prime factors, and assigns that value to "max"
max = p;
}
}
}
}
System.out.println(max); // prints the maximum prime-factor value.
sc.close();
}
}
我期望14的输出是7,但实际输出是1
最佳答案
你的素数检查错了。 c
仅当 c % j != 0
对于所有 1 < j < c 时才是素数。
int max=0,c=0;
for(int i=1;i<n;i++) {
if(n%i == 0) { //Checks for factors and assigns that value to "c"
c = i;
for(int j=2;j<c;j++) {
if(c%j==0) { // not prime
c = 0;
break;
}
}
if(max < c) { // if c > max, it must be > 0, which means it must be prime
max = c;
}
}
}
System.out.println(max); // prints the maximum prime-factor value.
关于JAVA程序求最大质因数,但输出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56664314/