判断给定两个数之间的素数个数,希望指正

问题遇到的现象和发生背景
#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;
}

有问题吗?

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632