vishalkin
vishalkin

Reputation: 1235

C program to print next five prime numbers

I have a program that prints five prime numbers within a user input range(m,n).

My problem is i want to print numbers greater than m. and print only next five numbers. I don't want to use upper limit.
How can I do it so?

#include <stdio.h>
#include <conio.h>

int main()
{
 int m,n,i,j,k,flag;


 printf("\nEnter The Lower Limit: ");
 scanf("%d",&m);
 printf("\nEnter The Upper Limit: ");
 scanf("%d",&n);

 printf("\nPrime Numbers Between %d & %d Are:\n",m,n);
 for(i=m ; i<=n ; i++)
 {
  k=i;
  flag=1;
  for(j=2 ; (j<=k/2)&&flag ; j++)
  {
   if(k%j==0)
   flag=0;
  }

  if(flag)
  printf("%3d \n",i);
 }


}

Upvotes: 0

Views: 4004

Answers (2)

Pandrei
Pandrei

Reputation: 4951

Whether you like it or not, you have a higher limit which is set by the data type you use -> int, in your case. Imagine you want the first 5 prime numbers larger than (MAXINT- 10)...you get the point, but let's assume you are not concerned about corner-cases.

int count=0;
int i=m;
int k;
while (count<5)
{
  k=i;
  flag=1;
  for(j=2 ; (j<=k/2)&&flag ; j++)
  {
   if(k%j==0)
   flag=0;
  }

  if(flag)
  {
     printf("%3d \n",i);
     count++;
  }

  i++;
}

Upvotes: 0

Cheeseminer
Cheeseminer

Reputation: 3068

Why not simply count the number of primes you have printed?

int count = 0;

:

for(i=m ; (i<=n) && (count<5) ; i++)

:

if(flag)
{
  printf("%3d \n",i);
  count++;
}

PS, using longer names than single characters will help make your program more understandable.

Upvotes: 2

Related Questions