Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am looking for an algorithm which helps me split a number $N$ as such:

$$N=p_1^a p_2^b \cdots p_n^z$$

where $N$ is the given number, $p$ is prime numbers smallest to greatest, and $a,b,\cdots,z$ are the power over the prime.

e.g. $10 = 2^1 \cdot5^1, \quad 20 = 2^2 \cdot5^1$.

share|cite|improve this question
You can write decent-looking formulae with the help of $\LaTeX$. – FrenzY DT. Oct 24 '12 at 11:33

Following is a Java method to achieve that. The idea is to try to divide the input number $N$ by the same divisor repeatedly starting from $2$ and keep a counter of the number of successful division, then increment the divisor. We don't need to check primality of the divisors as once we have reduced

$N$ to $\frac{N}{p^k}$ where $p^k||N$, the later is no longer divisible by any multiple of $p$.

For example, $N=504$

$\frac{504}2=252, \frac{252}2=126, \frac{126}2=63\implies 2^3||504$

$4$ can not divide $\frac{504}{2^3}=63$

$\frac{63}3=21, \frac{21}3=7 \implies 3^2||504$

$5$ does not divide $7$

$6$ can not divide $\frac{504}{2^3\cdot 3^2}=7$

$\frac 7 7=1\implies 7^1||504$

So, $504=2^3\cdot 3^2\cdot7^1$

    private static String primtFactors(long datum) {

       if (datum == 0)
            return "0";

       long datum2;

       StringBuilder msg = new StringBuilder();

       if (datum < 0) {
            datum2 = -datum;
       } else {
            datum2 = datum;

       if (datum2 == 1) {
       } else {
           for (long div = 2;;) {
            int count = 0;
            while (datum2 % div == 0) {
                datum2 /= div;

            if (count > 0) {
                count = 0;

            if (datum2 == 1)


       return msg.toString();


Sample output:







share|cite|improve this answer

I think, you need the Sieve of Eratosthenes: suppose $M$ is the max. number you want to split, then build a boolean array (IsItPrime[n]), and go from $1$ to $\sqrt M$ and strike out the multiples and mark as prime the next unstriked element. (Detailed in wiki.)

Once you have found the primes and you have an array of them, the factorization is straightforward (the cycle for looking for divisors can be restricted to primes only).

share|cite|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.