English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

given a positive integer 'n', print the 'nth' prime number. ex: the user inputs 3, the computer returns the value of 2, 3, 5. these are the first three prime numbers.im using c language...

2007-01-24 17:13:44 · 2 answers · asked by Sammy Baby 1 in Computers & Internet Programming & Design

2 answers

i am writing here only the loop required . rest you can write yourself.THIS IS SIMPLE AND MORE EFFICIENT THAN PREVIOUS ONE .

#include
#include
main()
{
int i,j,k,n;
printf("\nEnter the value of n:-");
scanf("%d",&n);

j=0;/*it will check for n prime nos.*/
for( i =2 ; ; i++)
{
for(k=2;k { if (i%k == 0)
break;
}
if (k==i)
{
printf("%d ",i); /* this is the prime no. */
j=j+1;/*increase no. of prime nos. displayed by one*/
}
if(j==n)
break;
}/*end of outermost for loop */

getch();
}/*end of function main*/

2007-01-24 17:49:06 · answer #1 · answered by Anonymous · 0 0

Try this one:

It will enter an integer and then print all the prime numbers up to the nth prime number. Change the size of the array if you want.


#include
#include
int is_prime(int n);
void main()


{
int num;
int i,j,k,s=2,flag,c_flag;
int array[100],count=0;
int r;
clrscr();
printf("Enter the number...");
scanf("%d",&num);
while(1)


{
if(num==1)
break;
r = num%s;
if(r==0)


{
array[count++] = s;
num = num/s;
}
else
s = s + 1;
while(1)


{
flag = is_prime(s);
if(flag==1)
break;
else
s = s + 1;
}
}
printf("The prime factors are.... ");
for(i=0;i printf(" %d ",array[i]);
getch();

}
//Function for checking whether the numb
// er is prime or not.
int is_prime(int s)


{
int i,j=0,k=0;
for(i=1;i<=s;i++)


{
j = s%i;
if(j==0)
k++;
}
if(k==2)
return 1;
else
return 0;
}

2007-01-25 01:30:35 · answer #2 · answered by Anonymous · 0 0

fedest.com, questions and answers