I am presently reading a beautiful book, "The Haskell Road To Logic Maths and Programming" by Kees Doets and Jan Van Eijck. I would highly recommend this book to any serious student of Computer Science. I plan to talk on prime numbers as that's what I read yesterday.
Here's a brief background on prime numbers. Well a prime number is a number that does not have factors other than itself and 1. For example lets take a number 7, as the number 7 does not get cleanly divided by any number except 1 and 7 hence it is a prime. Similarly the number 8, is divided cleanly by 2 and 4 hence it is not a prime.
Some applications of prime number are in the field of RSA encryption.
There are many ways to find if a given number is prime or not. One commonly used way is to run a for loop starting from 2 up-till the number/2+1, in case of a clean division we declare that the number is not a prime. This method works great for small numbers, but just imagine the amount of work that needs to be done to find if a very large number is a prime number or not.
We will state 2 propositions and write a small java program based on the proposition to find if a given number is prime number.
Let us define a number L(n)>1 as the least natural number that divides n.
Proposition 1:
for L(n) > 1 L(n) is a prime.
We will prove this proposition through a process called contradiction.
Let p=L(n).
In case p is not a prime, we can factor it such that:
a*c=p; which follows a > 1 and c < p.
Hence the least possible number dividing n must naturally be a prime.
Proposition 2:
for n>1 and n is not a prime, (L(n))^2<=n
So let's prove this one as well.
Let p=L(n).
As p is a factor of n, it follows.
a*p=n. for some number a such that
a > = p ----------------1
as p is the least natural number dividing n.
Multiplying both sides of 1> by p, we get
a.p >= p^2; substituting a.p=n and p^2=(L(n))^2 we get
Which basically means that the square of the least prime factor of a number is always less than or equal to the number.
Here's is the java implementation, enjoy:
package algos;
public class IsPrime {
public static boolean isPrime(int number)
{
boolean flag=true;
for(int i=2; i <= number; i++)
{
if(number%i==0)
{
flag=false;
break;
}
if((i*i)>=number)
{
flag=true;
break;
}
}
return flag;
}
public static void main(String[] args) {
System.out.println(isPrime(23));
}
}
No comments:
Post a Comment