The first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 5th prime is 11.
What is the 10001st prime number???
This Question is quit direct but we try to solve it in very effective way.
i.e with less complexity .
What is the 10001st prime number???
This Question is quit direct but we try to solve it in very effective way.
i.e with less complexity .
First Of all we need to know best way to check a number is prime or not. Read this Play With Prime .
Now We gonna use similar approach as we use to check isPrime or not.
i.e at least we can escape all even number before checking.
Algorithm:
- initially initially count=1 (we count=1 as 2 is prime but we r not gonna calculate it in our program)
- initialize i=3 (start checking prime from 3)
- while( i < n){ if i is prime increment count by 1 , increment i by 2 after each loop}
- i-2 is our required prime number
Here we eliminate almost half of number before checking it is prime or not.
C-Program To find n'th Prime Number:
- //C-Program to find n'th prime number
- //www.codecops.in
- #include<stdio.h>
- #include<math.h>
- int isPrime(int n){
- /*
- *****<math.h>
- this Function take n is input
- & return 1 if n is prime else return 0
- */
- int i,sqrt_n,flag=1;
- sqrt_n=(int)sqrt(n); //squire root of n
- sqrt_n++;
- 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)
- }
- int main(){
- int count=1; //we include 2 as first prime number
- int i,n;
- printf("\nEnter Value of n :");
- scanf("%d",&n);
- i=3;//avoid checking even numbers by incrementing index by 2
- //after each itteration
- while(count<n)
- {
- if(isPrime(i)){
- count++;
- }
- i=i+2;
- }
- printf("\nnth prime number is %d",i-2);
- }
Please Suggest ,
Thank U
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT