How to save all the outputs of a for loop - java

419 views Asked by At

In java i am trying to make a program to do my math homework (not to actually cheat, just trying to learn java) and i have a for loop that gets me all the factors of the given number, but i can't figure out how to save all of the outputs of the for loop in pairs ( if possible) to test later in the math problem to solve it, here is the code. (will add needed info on request, first post)

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;
        } 
    }

}

}
2

There are 2 answers

0
Lutz Lehmann On

There is a much easier way to compute the greatest common factor or divisor, called the Euclidean algorithm.

int gcd(int a, int b) {
    while(0 != b) {
        r = a%b; a = b; b = r;
    }
    return a;
}
0
vineeth sivan On

You can use file to save your result.

try the following code

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);
        }
    } 
}