Prime numbers :- Numbers that are only divisible by 1 and by itself .
Now think how to check number is prime or not
Now think how to check number is prime or not
Basic Approach
Check Divisibility of number form 2 to n-1 is it is not divisible then prime .
- #Just check for divisibility by all No except 1 & n
- def isPrime_basic(n):
- for i in range(2,n):
- if n%i==0:
- return False
- return True
- if __name__=='__main__':
- n=raw_input('Enter No to test isPrime :- ')
- print isPrime_basic(int(n))
but you can imagine complexity increase with value of n .So we need to find some better Approach
Better Approach
We can make above code run faster by noticing that we only need to check divisibility for values of i that are less or equal to the square root of n. { Think Why ?? }
And
As we know 2 is only even prime Number . so remove all multiple of 2 because they are not prime and if a number is not divisible by 2 then it will also not divisible by any other even Number.
- def isPrime(n):
- if n<=1:
- return False
- elif n==2:
- return True
- elif n%2==0:
- return False
- elif n>2:
- for i in range(3,n,2):
- if n%i==0:
- return False
- return True
- if __name__=='__main__':
- n=int(raw_input('Enter number to check isPrime :- '))
- print isPrime(n)
Fastest Technique to find all prime no below given Number :
This technique is known as sieve of eratosthenes . In this Technique
- Create list of number from to to n.
- find first prime then remove all its multiple from the list Ex: 2 is first prime number then remove 4,6,8,10 ... from the list. similarly remove multiple of next prime numbers like next prime number is 3 . Now remove its multiple i.e. 6,9,12,15 ...
- Repeat process until reach to the end of list
- Remaining element in list is prime numbers
A sample Program in C++ for this . This is cheapest implementation this algorithm but You can use this program to understand this algorithm.
- //C++ Program to calculate prime number between between 1 to 300
- #include<iostream>
- #include<math.h>
- using namespace std;
- #include<stdio.h>
- #include<math.h>
- int isPrime(int n){
- int i,sqrt_n,flag=1;
- sqrt_n=(int)sqrt(n); //squire root of n
- sqrt_n++; //approximating
- if(n<2){
- return 0; //return False
- }
- else{
- if(n==2){
- return 1; //return True
- }
- else if(n%2==0)
- return 0;
- }
- for(i=3;i<sqrt_n;i=i+2){
- if(n%i==0){
- flag=0;
- break;
- }
- }
- return flag; //return value of flag 0(false) or 1(true)
- }
- main(){
- int arr[300];
- int i,j;
- for(i=1;i<300;i++){
- arr[i]=i+1;
- }
- arr[0]=-1; //special case for 1
- for(i=0;i<300;i++){
- if(arr[i]!= -1){
- if(isPrime(arr[i])==0){
- arr[i]==-1;
- }
- else{
- for(j=i+arr[i];j<300;j=j+arr[i]){
- arr[j]=-1;
- }
- }
- }
- }
- //print prime no
- cout<<"prime no are :-"<<endl;
- for(i=0;i<300;i++){
- if(arr[i]!= -1){
- cout<<" "<<arr[i];
- }
- }
- }
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT