#include <bits/stdc++.h>
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
int count = 0;
if(x > y)
{
swap(x, y);
}
for (int i = x; i <= y; i++)
{
bool ans = true;
for (int j = 2; j <= i / 2; j++)
{
if(i % j == 0)
{
ans = false;
break;
}
}
if(ans == true)
{
count++;
}
}
cout << count;
return 0;
}
你没有对i = 1的情况处理
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
int count = 0;
if(x > y)
{
swap(x, y);
}
for (int i = x; i <= y; i++)
{
bool ans = true;
if (i<=1) // 对i = 1的情况处理
{
ans = false;
}
for (int j = 2; j <= i / 2; j++)
{
if(i % j == 0)
{
ans = false;
break;
}
}
if(ans == true)
{
count++;
}
}
cout << count;
return 0;
}
你用两个很大的数字测试一下
#include <iostream>
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
int count = 0;
if (x > y)
{
swap(x, y);
}
for (int i = x; i <= y; i++)
{
bool ans = true;
for (int j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
ans = false;
break;
}
}
if (ans == true)
{
count++;
}
}
cout << count;
return 0;
}
有问题吗?
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!