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++;
}
}
}
This is the code for displaying 21 = 3 * 7. I would be grateful if you could give me some advice.
Recommended Posts