So I am trying to write a factor generator. User provides an integer and program needs to return all factors. I have found an example the code that does this function, but I can't understand how it does that. Please explain line by line how this works.
System.out.print("Enter an integer:
");
int number = input.nextInt();
int index = 2;
//Prompts user for an integer and assigns it to variable number, and integer index is declared as 2.
while (number / index != 1) {
// While number divided by integer isn't equal to 1?
if
(number % index == 0) {
//If remainder of number divided by index is 0?
System.out.print(index + ",
");
//Prints variable index and a comma
number /= index;
//divides number by index and puts returned value back into
number?
}
else
index++;
//adds one to index?
}
System.out.println(number +
".");
//prints number and a dot.
So let me explain all the code line by line:
System.out.print("Enter an integer: ");
This line is used to print a statement which says "Enter the integer: "
int number = input.nextInt();
This line is used to take an input with the datatype as int and assign the value to the variable number.
int index = 2;
This variable index ie. the index is assigned the value 2.
while (number / index != 1) {
We starts a while loop and the program comes out of the while loop when the value of (number/index) becomes equal to 1. Then we comes out of the while loop.
if (number % index == 0) {
We get into this if block when the remainder, when we divides the number by index is equal to zero, ie. the index is completely divisible by number and dont leave any remainder. for ex 4 is divisible by 2 and don't leave any remainder but if we divide 4 with 3 we gets a remainder which is 1.
System.out.print(index + ", ");
We prints the value of index because if it completely divisible by the number then it means it is the factor of the number.
number /= index;
We divides the number with the index so that a new number comes because if the number is divisible by the current index then it'll by divisible by all of the multiples of index too.
else
index++;
If the index is not divisible by the number so increment it so we can see whether it is divisible by the next number or not.
The While loop while run till the index is equal to the number, then (number/index) == 1 and the while loop comes out.
System.out.println(number + ".");
So after the while loop ends we print the value of number too, which will be equal to the index too as every number is a factor of itself too. And this ends our program.
Thank you so much.
Get Answers For Free
Most questions answered within 1 hours.