calculate prime factors of a number java
public static void main(String[] args) {
int n=12;
for(int i=2; i<=n; i++){
while(n%i==0){
n=n/i;
System.out.println(i); //prints 2 2 3
}
}
}
calculate prime factors of a number java
public static void main(String[] args) {
int n=12;
for(int i=2; i<=n; i++){
while(n%i==0){
n=n/i;
System.out.println(i); //prints 2 2 3
}
}
}
How to find the prime factors of a number in Java?
public class PrimeFactorization {
/*
* Aim is to find all the prime
* factors of a given number n
*/
public static void main(String[] args) {
int value = 315;
printPrimeFactors(value); // 3^2 5^1 7^1
}
private static void printPrimeFactors(int n) {
int powerOfDivisor;
// Identify the prime factors of n
for (int div = 2; div * div <= n; div++) {
if (n % div == 0) {
powerOfDivisor = 0;
// How many times prime factor divides n
while (n % div == 0) {
n = n / div;
powerOfDivisor++;
}
// Print prime factor raised to a certain power
System.out.print(div + "^" + powerOfDivisor + " ");
}
}
// Last prime factor of n has a power = 1
if (n > 1)
System.out.println(n + "^" + 1);
else
System.out.println();
}
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us