forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request TheAlgorithms#1300 from vtolas/master
Add prime factorization algorithm in /maths
- Loading branch information
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package Maths; | ||
|
||
import java.lang.Math; | ||
import java.util.Scanner; | ||
|
||
public class algorithm { | ||
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); | ||
} | ||
public static void pfactors(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); | ||
} | ||
} |