-1

I am using this following code to find 10001th prime number but it is not running.
I am using devc++, but when I run this code, a blank screen comes up.

This is my Code:

#include<iostream>
#include<conio.h>
using namespace std;
int prime(int a)
{
    int p=0;
    for(int j=2;j<=a/2,p<=0;j++)
    {
        if(a%j==0)
        {
            p++;
        }
    }
    if(p==0)
    {
        return 1;
    }
    else
    return 0;
}

int main()    
{
    int i,c=0;
    for(i=2;c<=10001;i++)
    {
        if(prime(1))
        {
            c++;
        }
    }
    cout<<i;
    return 0;
}
Arun A S
  • 6,421
  • 4
  • 29
  • 43
Anonymous
  • 13
  • 1

3 Answers3

1

point 1:
you are passing if(prime(1)) argument 1 every time change this line to

if(prime(i))

point 2: Change this line

for(int j=2;j<=a/2,p<=0;j++)

To

for(int j=2;(j<=a/2 && p<=0);j++)

Point 3:
Change this line

cout<<i;

To

cout<<i-1;  // as at the end of `for` loop it will increment to `1` so print `i-1`.
Himanshu
  • 4,327
  • 16
  • 31
  • 39
0

First of all , I think you meant

if(prime(i)) 

instead of if(prime(1))

Secondly, there are many gaps in this code .. First, you can verify if the number a divides by j with j taking a maximum value of sqrt(a) (using math.h library) , it would be faster when working with higher values. Another thing, you said this is a code for finding the 10001th prime number not the number of prime numbers until 10001 and cout<<i; in the end doesn't make any sense, I think you meant cout<<c;

A.D.
  • 66
  • 1
  • 2
0

Let's look at each problem.

First, you need to use

if( prime(i) )

instead of

if( prime(1) )

I believe that was a typo on your part.

Second, as i is incremented after the for loop, you need to change

cout << i;

to

cout << i-1;

Third, the comma operator only executes the expression at the end. What you need here is &&. So change

for(int j = 2 ; j <= a/2 , p <= 0 ; j++)

to

for(int j = 2 ; j <= a/2 && p <= 0 ; j++ )

For more info on the comma operator, see Uses of C comma operator

Lastly, change

for( i = 2 ; c <= 10001 ; i++ )

to

for( i = 2 ; c < 10001 ; i++ )

Otherwise, you will get the 10002th prime number.

These should fix your problem.

Community
  • 1
  • 1
Arun A S
  • 6,421
  • 4
  • 29
  • 43