在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;
}
}
}
}
最佳答案
有一种更简单的方法来计算最大公因数或除数,称为欧几里得算法。
int gcd(int a, int b) {
while(0 != b) {
r = a%b; a = b; b = r;
}
return a;
}
关于java - 如何保存for循环的所有输出 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35308837/