Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

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
       }
   }
}
Comment

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();
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: does finally block executed after crash 
Java :: hello world java code 
Java :: android remove focus from an element 
Java :: Add delay to code in Android 
Java :: date minus date java 
Java :: spinner get selected index 
Java :: number of digits java 
Java :: java array loop 
Java :: isnull java 
Java :: spring boot base url 
Java :: java array initialization 
Java :: java convert array to list 
Java :: redondear a 2 decimales java 
Java :: testing the web layer without authentication spring 
Java :: useColorScheme returning light 
Java :: sort list java 8 
Java :: synchronized java 
Java :: java read file 
Java :: java replace character 
Java :: java string to integer 
Java :: java convert edittext to double 
Java :: Java Writer Using FileWriter 
Java :: java printf tab 
Java :: java get attributes from class 
Java :: check stack empty java 
Java :: flink prometheus alert on failed jobs 
Java :: Java Sorting Using sort() 
Java :: error: package android.support.v7.app does not exist 
Java :: java print default options 
Java :: rock paper scissor in java 
ADD CONTENT
Topic
Content
Source link
Name
2+4 =