Prime Factorization Program Java

时间:2014-03-26 17:37:09

标签: java math primes prime-factoring

这些是我对该计划的指示:

编写一个程序,要求用户输入一个整数(使用JOptionPane),然后输出其素数分解。

例如,当用户输入150时,程序应打印“Prime factorization of 150:2 3 5 5”。

使用类FactorGenerator和方法nextFactor和hasMoreFactors(谓词方法)。实例字段应为数字和因子。 hasMoreFactors方法应该将factor初始化为2并使用while循环来递增factor,直到factor均匀地划分为数字(在这种情况下hasMoreFactors返回值为true)或者factor变得太大(在这种情况下hasMoreFactors返回值false)。

在FactorGeneratorTest中,应允许用户输入他/她希望的整数。输入应继续,直到按下取消按钮。建议您输入的整数为30,100,2310和27225。

到目前为止,这是我的FactorGenerator类:

package primeFactorization;

public class FactorGenerator {

public FactorGenerator(double input) {
    number = input;
}

public String hasMoreFactors() {
    factor = 2;
    boolean loop = true;
    primeFactors = "Prime Factors are: ";
    while(loop) {
        if(number % factor == 0) {
            number = number / factor;
            primeFactors = (number + ", ");
            }
            if(factor > number) {
                loop = false;
            }
            if(number % factor != 0) {
                factor++;
            }
            if(number < 2) {
                loop = false;
            }
        }
        return primeFactors;
    }

    private String primeFactors;
    private boolean hasFactor;
    private double number;
    private double factor;
}

这是我的测试课:

package primeFactorization;

import javax.swing.JOptionPane;

public class FactorGeneratorTest 
    {
    public static void main(String[]args) {
        String input = JOptionPane.showInputDialog("Enter a number. ");
        Double num = Double.parseDouble(input);

        FactorGenerator factors = new FactorGenerator(num);

    System.out.println(factors.hasMoreFactors());
}
}

我该如何开展这项工作?

2 个答案:

答案 0 :(得分:1)

您正在将hasMoreFactors()方法中的String变量primeFactors重新分配给变量number的中间值。 primeFactors应与素因子的值(即可变因子的值)连接在一起。 hasMoreFactors()应如下所示:

public String hasMoreFactors() {
        factor = 2;
        boolean loop = true;
        primeFactors = "Prime Factors are: ";
        while (loop) {
            if (number % factor == 0) {
                number = number / factor;
                primeFactors += (factor + ", ");
            }
            if (factor > number) {
                loop = false;
            }
            if (number % factor != 0) {
                factor++;
            }
            if (number < 2) {
                loop = false;
            }
        }
        return primeFactors;
    }

答案 1 :(得分:0)

实施例: 输入为35,您从因子2开始,但35 % 2 = 1,所以您永远不会来factor++ 把它直接放到循环的末尾,并询问是否在该回合中找不到因子。