在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;
}
}
}
}发布于 2016-02-10 19:09:35
有一种更简单的方法来计算最大公因子或除数,称为欧几里德算法。
int gcd(int a, int b) {
while(0 != b) {
r = a%b; a = b; b = r;
}
return a;
}发布于 2016-02-10 15:44:42
您可以使用file保存结果。
尝试以下代码
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);
}
}
}https://stackoverflow.com/questions/35308837
复制相似问题