I've been taking Java lectures in earnest since the day before yesterday, and I learned about do-while statements. I decided to write a prime factorization program, so this is a memorandum. (Based on the primality test program I wrote yesterday.)

`Soinsu.java`

```
package sample_0306;
import java.util.Scanner;
public class Soinsu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num;
System.out.println("Prime factorization");
while (true) {
System.out.print("Please enter an integer greater than or equal to 2. :");
num = sc.nextInt();
if (num < 2) {
System.out.println("An integer less than 2.");
} else
break;
}
int x = num;
System.out.print(num + " = ");
for (int i = 2;i <= num;) {
if (x % i == 0) { //Find the smallest factor
System.out.print(i);
if (x != i)
System.out.print(" * "); //Stop inserting * when x and the factor are equivalent
x /= i; //Substitute the number divided by the smallest factor
} else
i++;
}
}
}
```

- Play the while statement whose input content is less than 2 and have it re-entered.
- Escape the while statement with break, and judge if the input is 2 or more with the if statement.
- Divide in order from 2, and if it is divisible, display the number.
- If x and the factor are not equivalent (still can be factored into prime factors), * is displayed.
- If it is not divisible, add 1 to i and loop.

This is the code for displaying 21 = 3 * 7. I would be grateful if you could give me some advice.

Recommended Posts