JAVA程序求最大质因数,但输出错误?

标签 java primes factors

我已经返回代码(用 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/

相关文章:

java - vtd-xml 的编码问题

java - 为什么 Windows 10 上的一个 Java 程序会运行 2 个 Java 平台二进制文件?

C++ - 成对显示的整数因子

Python Pollard P-1 分解

algorithm - nᵗʰ丑数字

r - 为什么 Filter 无法提取数字的因数?

java - 在 WebLogic 上调试 session 创建

java - Netstat 用于单个连接?

c - 我使用埃拉托色尼筛作为素性测试。为什么我得到 2297 是复合数?

c - 比 int 更大的数的质因数分解