Sunday, August 2, 2009

Help me please?! prime number in c++?

is it possible to write the same program wit same commands without flag and also please describe flag





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








int main(void){


int j,n,i,flag;


printf("Please enter a number : ");


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


if(n%26lt;2) {


printf("\nNo prime numbers available");


return 1;}


printf("Thank you : 2");


for(i=2;i%26lt;=n;i++){


for(j=2;j%26lt;=i-1;j++){


if(i%j==0){


flag=0;


break;}


flag=1;


}


if(flag==1)


printf("%5d",i);


}





return 0;


}

Help me please?! prime number in c++?
u need atleast one flag variable. I have reduced ur code. wat i have given is very simple code.





please correct the syntax. but the logic is correct.





flag=1;





for(i=2;i%26lt;n-1;i++){


if(n%i==0){


flag=0;


break;


}


}


if(flag==1){


printf("prime");


}


else


printf("not a prime");








//Note:-


/*


n is the number for which it has to be checked for prime.


flag=1 (initially assuming that the given number is prime and reinitializing to 0 after checking the condition in if loop.


*/
Reply:Yes. Instead of for loops you should be using while loops. The flafg here is only used for breaking the loop. You will not need it if you use while loop.





i =2;


while(i%26lt;=n)


{


j=2;


while (j%26lt;=i-1)


{


if (I%j++ == 0)


{


break; // this will break the loop for j


}


}// end of while for j





if (j == i) printf("%d ",i);


i++;


} //end of while for i


}
Reply://try this


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


void main()


{


int n,i,flag;


flag=0;


printf("Enter the Number:\t\t");


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


if(n%26lt;2)


printf("\n%d is not prime",n);


else


{


for(i=0;i%26lt;n/2;++i)


{


if(n%i)


flag=1;


}





if(flag)


printf("%d is not prime",n);


else


printf("%d is prime",n);


}


getch();


}


No comments:

Post a Comment