Prime Factor of any number.

Prime Factor of any number.

Previous Home Next

 

Following program for Provide the Prime factor of any input number.

 

 
/*
 * Save as a Factorial.java
 * Program for the prime factorization of any number.
 */
package r4r.co.in;

import java.io.*;

public class Factorial {

    public static void main(String[] args) throws IOException {

        BufferedReader d = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the Digit/Number:");
        String s = d.readLine();
        long n1 = Long.parseLong(s);      //Type conversion(string into long)

        // Code for prime factorization
        System.out.print("The prime factorization of " + n1 + " == ");
        for (long i = 2; i <= n1 / i; i++) {

            // Input digit(n1) is divisible by i, until the output==1
            while (n1 % i == 0) {
                System.out.print(i + " x ");
                n1 = n1 / i;
            }
        }

        // if n1 > 1,the loop is again compile
        if (n1 > 1) {
            System.out.println(n1);
        } else {
            System.out.println("\n" + n1);
        }
    }
}

Enter the Digit/Number:
220
The prime factorization of 220 == 2 x 2 x 5 x 11
Previous Home Next