Sunday, August 9, 2015

prime number brute force

Prime number :-
          Each natural number that is divisible only by 1 and itself is prime. Prime numbers appear to be more interesting to humans than other numbers. A natural number (i.e. 1, 2, 3, 4, 5, 6, etc.) is called a prime number (or a prime) if it has exactly two positive divisors, 1 and the number itself for big numbers. The property of being prime (or not) is called primality. If we want to know whether n is prime the very basic approach is to check every single number between 2 and n. It’s kind of a brute force.
       Brute force method of finding the prime is not very efficient to check a big number is prime or not. There many efficient algorithms to check a big number is prime or not, that we will study in later articles.

Below is the implementation of brute force method to check given number is prime number or not.

package com.techguy.algo;

/**
 * @author techguylearning@gmail.com
 *
 */
public class PrimeNumberBruteForce {


public static void main(String[] args) {
System.out.println(new PrimeNumberBruteForce().isPrime(9839876));
}
public boolean isPrime(int n){
int i = 2;
if(n<2){
return false;
}
if(2==n){
return true;
}
while( i < n){
if(n % i == 0){
return false;
}
i++;
}
return true;
}

}




No comments:

Post a Comment