mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 09:06:51 +08:00
Add prime factorization algorithm (#3278)
This commit is contained in:
@ -1,35 +1,39 @@
|
||||
package com.thealgorithms.maths;
|
||||
|
||||
import java.util.Scanner;
|
||||
/*
|
||||
* Authors:
|
||||
* (1) Aitor Fidalgo Sánchez (https://github.com/aitorfi)
|
||||
* (2) Akshay Dubey (https://github.com/itsAkshayDubey)
|
||||
*/
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PrimeFactorization {
|
||||
|
||||
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();
|
||||
}
|
||||
public static List<Integer> pfactors(int n) {
|
||||
|
||||
List<Integer> primeFactors = new ArrayList<>();
|
||||
|
||||
public static void pfactors(int n) {
|
||||
if (n == 0) {
|
||||
return primeFactors;
|
||||
}
|
||||
|
||||
while (n % 2 == 0) {
|
||||
System.out.print(2 + " ");
|
||||
n /= 2;
|
||||
}
|
||||
while (n % 2 == 0) {
|
||||
primeFactors.add(2);
|
||||
n /= 2;
|
||||
}
|
||||
|
||||
for (int i = 3; i <= Math.sqrt(n); i += 2) {
|
||||
while (n % i == 0) {
|
||||
System.out.print(i + " ");
|
||||
n /= i;
|
||||
}
|
||||
}
|
||||
for (int i = 3; i <= Math.sqrt(n); i += 2) {
|
||||
while (n % i == 0) {
|
||||
primeFactors.add(i);
|
||||
n /= i;
|
||||
}
|
||||
}
|
||||
|
||||
if (n > 2) {
|
||||
System.out.print(n);
|
||||
}
|
||||
}
|
||||
if (n > 2) {
|
||||
primeFactors.add(n);
|
||||
}
|
||||
return primeFactors;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user