c++判断素数的问题

来源:百度知道 编辑:UC知道 时间:2024/04/29 12:30:02
#include <math.h>
#include <iostream.h>
main()
{
int x,i;
cin>>x;
while (x>0)
{
for(i=2;i<=x-1;i++)
if(x%i==0)
{
cout<<"是素数"<<endl;
break;}
else
{cout<<"不是素数"<<endl;
break;}
}
return 0;}
完成之后运行无限有重复运算,是什么问题呢???

你 判断语句 while(x>0) 永远是真。因为x 的值没有变

基本上这个程序是完全是错的...

我大概写个思路,你自己做完

i = 0;
for (i = 2; i <= x-1; i++){
if (x % i == 0) {
cout << "不是素数" << endl;
return;



cout << "是素数" << endl;
return

前面的while 不要了

for(int i=0;i<sqrt(x);i++)
if(x%i==0) {cout<<"非素数"<<endl;return;}
cout<<"素数"<<endl;

#include "math.h"