0

在java中,我正在尝试制作一个程序来完成我的数学作业(实际上并不是作弊,只是想学习java)并且我有一个for循环可以让我得到给定数字的所有因素,但我无法弄清楚如何成对保存 for 循环的所有输出(如果可能)以便稍后在数学问题中进行测试以解决它,这里是代码。(将根据要求添加所需的信息,第一次发布)

import java.util.Scanner;

public class factoring {

public static void main(String[] args) {
    String varible;
    String secondOperator;
    String firstOperator;
    int power;
    int greatestCommonFactor;
    long factorTo;
    long factorBy;
    String factors = null;
    Scanner userInput = new Scanner(System.in);

    System.out.println("Please enter the greatest common factor (Default to 1)");
    greatestCommonFactor = userInput.nextInt();

    System.out.println("Please input the varible");
    varible = userInput.next();

    System.out.println("Please enter the power");
    power = userInput.nextInt();

    System.out.println("Please enter the first operator");
    firstOperator = userInput.next();

    System.out.println("Please enter what your factoring to");
    factorTo = userInput.nextInt();

    System.out.println("Please enter the second operator");
    secondOperator = userInput.next();

    System.out.println("Please enter what you're factoring by");
    factorBy = userInput.nextInt();

    for(int i = 1; i * i <= factorBy; i++) {
        if (factorBy % i == 0) {
            if (i * i != factorBy) factors = factorBy / i + " and " + i;
        } 
    }

}

}
4

2 回答 2

1

有一种更简单的方法可以计算最大公约数或除数,称为欧几里得算法。

int gcd(int a, int b) {
    while(0 != b) {
        r = a%b; a = b; b = r;
    }
    return a;
}
于 2016-02-10T11:09:34.687 回答
0

您可以使用文件来保存结果。

试试下面的代码

String  loc = "Desktop/Factors of "+factorBy;
File outFile = new File(loc);

if(!outFile.exists())
{
    outFile = new File(loc);
}
try{

    fout = new FileOutputStream(outFile);
}
catch(Exception e){
    e.printStackTrace();
}


for(int i = 1; i * i <= factorBy; i++) {
    if (factorBy % i == 0) {
        if (i * i != factorBy){
            factors = factorBy / i + " and " + i;


            try{
                fout.write(factors.getBytes());
                fout.write("\n".getBytes());

            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            System.out.println("factors:"+factors);
        }
    } 
}
于 2016-02-10T07:44:42.153 回答