Prime Numbers in Java - Algorithms

前端 未结 6 886
南笙
南笙 2021-01-22 15:48

I have started learning to code in Java and decided I would use the Project Euler site to give me little tasks to try and complete with each bit of new coding I learn. So I came

6条回答
  •  后悔当初
    2021-01-22 16:43

    What you can do is find the lowest divisor of Tn. Suppose that is p, find the lowest divisor again for Tn/p and so on.

    Now, at every step p is prime[explanation below]. So collect them and they are the prime divisors of Tn.

    For better time-complexity, you can check for divisors up to upto ceil(sqrt(Tn)) only, instead of Tn-1.

    And when you start checking for prime divisor for Tn, you can start with 2. And once you get a prime divisor p don't start again from 2 for Tn/p. Because, Tn/p is also a divisor of Tn and since Tn does not have divisors less than p, Tn/p does not have it too. So start with p again[p can have multiple power in Tn]. If p does not divide Tn, move to p+1.

    Example :

    Tn = 45
    1. start with 2. 2 does not divides 45.
    2. next test is for 3. 45 is divisible by 3. So 3 is a prime divisor of it.
    3. Now check prime divisors from 45/3 = 15, but start with 3. not from 2 again. 4. Well, 15 is divisible by 3. So start with 15/3 = 5 5. Note for 5, ceil(sqrt(5)) is 3. But 5 is not divisible by 3. But since 4 > ceil(sqrt(5)) and we can say 5 is a prime without any doubt.

    So the prime divisor of 45 are 3 and 5.


    Why smallest divisor(except 1) of a number is a prime ?

    Suppose above statement is false. Then a number N has a smallest yet composite divisor, say C.

    So C|N Now C is composite so, it has divisor less than itself but greater than one.
    Say such a divisor of C is P.
    So P|C , but we have C|N => P|N where 1 < P < C.

    This contradicts our assumption that C is the smallest divisor of N, so smallest divisors of a number is always a prime.

提交回复
热议问题