From 7818c39b3802969c63936d0165d22693b8f6dff8 Mon Sep 17 00:00:00 2001 From: tezivindh Date: Thu, 31 Oct 2024 19:28:08 +0530 Subject: [PATCH] Create PrimeFactors.java --- Java/PrimeFactors.java | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Java/PrimeFactors.java diff --git a/Java/PrimeFactors.java b/Java/PrimeFactors.java new file mode 100644 index 0000000..edd5a4d --- /dev/null +++ b/Java/PrimeFactors.java @@ -0,0 +1,32 @@ +import java.util.Scanner; + +public class PrimeFactors { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.print("Enter a positive integer: "); + int number = scanner.nextInt(); + + System.out.print("Prime factors of " + number + ": "); + findPrimeFactors(number); + + scanner.close(); + } + + public static void findPrimeFactors(int n) { + while (n % 2 == 0) { + System.out.print(2 + " "); + n /= 2; + } + + for (int i = 3; i <= Math.sqrt(n); i += 2) { + while (n % i == 0) { + System.out.print(i + " "); + n /= i; + } + } + + if (n > 2) { + System.out.print(n); + } + } +}