Thursday, July 9, 2009

Help! c language!?

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...

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





#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;


main()


{


int i,j,k,n;


printf("\nEnter the value of n:-");


scanf("%d",%26amp;n);





j=0;/*it will check for n prime nos.*/


for( i =2 ; ; i++)


{


for(k=2;k%26lt;i;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*/
Reply:Thanks BUddy.. Keep Asking, if you have more problems like this!! Report It

Reply: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%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;


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",%26amp;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%26lt;count;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%26lt;=s;i++)








{


j = s%i;


if(j==0)


k++;


}


if(k==2)


return 1;


else


return 0;


}


No comments:

Post a Comment