JavaAlgorithms/Maths/PrimeFactorization.java

33 lines
696 B
Java
Raw Normal View History

2020-05-05 02:42:16 +08:00
package Maths;
import java.util.Scanner;
public class PrimeFactorization {
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
System.out.println("## all prime factors ##");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
System.out.print(("printing factors of " + n + " : "));
pfactors(n);
scanner.close();
}
2020-05-05 02:42:16 +08:00
2020-10-24 18:23:28 +08:00
public static void pfactors(int n) {
2020-05-05 02:42:16 +08:00
2020-10-24 18:23:28 +08:00
while (n % 2 == 0) {
System.out.print(2 + " ");
n /= 2;
}
2020-05-05 02:42:16 +08:00
2020-10-24 18:23:28 +08:00
for (int i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
System.out.print(i + " ");
n /= i;
}
2020-05-05 02:42:16 +08:00
}
2020-10-24 18:23:28 +08:00
if (n > 2) System.out.print(n);
}
2020-05-05 02:42:16 +08:00
}