我的质数检查器怎么了?

Whats wrong with my Prime number Checker?

本文关键字:怎么了 检查 我的      更新时间:2023-10-16

我创建了一个素数检查程序,检查用户输入的数字是否为素数。

它很容易检测到非素数,但是当我们输入素数时,它崩溃了!

我想我知道为什么,但不知道如何纠正它们…

这是我的程序:

#include "stdafx.h"
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;

float Asker()
{
    float n;
    cin >> n;
    return n;
}

int Remainder(int n, int x)
{
    int q = n%x;
    if (q == 0)
        return 1;
    else
        Remainder(n, x + 1 > n);
    /* 
    Here is the PROBLEM
    */
    return 0;
}

int main()
{
    cout << "Enter your Number : ";
    float n = Asker();
    int r = Remainder(n, 2);
    if (r == 1)
        cout << "That Ain't Prime!n";
    else
        cout << "Yep Thats Prime!n";
    main();
    return 0;
}

假设,当我输入7,我知道,它检查到6,那么它应该崩溃!(由于x + 1> n的条件)。我不知道如何在else条件失败时返回0

回答你的问题"我的质数检查器出了什么问题?"很多事情都是错的:

  • 不要调用main中的main()。递归不是这样的
  • int Remainder(int n, int x),您使用float(缺少cast)然后使用bool调用它:Remainder(n, x + 1 > n);
  • 你的asker不需要是一个浮动

关于main内的递归,有两个原因:

  • 使用这个配置你将得到一个无限循环;
  • ISO c++禁止接受函数'::main'的地址

//#include "stdafx.h"   //This is an invalid header.
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;

float Asker()
{
    float n;
    cin >> n;
    return n;
}

int Remainder(int n, int x)
{
    int q = n%x;
    if (q == 0 && n>2 )//'2' have to be excluded.
                   //otherwise 2%2==0 can set
                   //'2' as a non prime which is wrong
        return 1;
    else if(x+1<n)
        Remainder(n, x + 1);
    /*
    Here was the PROBLEM
    Remainder(n, x + 1 > n) 'x + 1 > n ' is an invalid paramrter.
    */
    else
        return 0;
}
    int main()
{
    cout << "Enter your Number : ";
    float n=Asker();
    int r=1;        //It is essential to initialize r to 1
    if(n!=1)        //Have to exclude '1'. Otherwise
                //It will assign '1' as prime which is wrong
        r = Remainder(n, 2);
    if (r == 1 )
        cout << "That Ain't Prime!n";
    else
        cout << "Yep Thats Prime!n";
    //main();   //Why are you calling main again?
    return 0;
}
    你的第一个错误是" #include "stdafx.h"。你从哪弄到这个头的?在int Remainder(int n, int x)函数中,你使用了递归并发送了一个无效的语法"Remainder(n, x + 1> n)"。"。你不能在参数中使用x+1>n这样的语法。
  1. 之后,为什么你在main函数内调用main() ?你的算法需要一些改进我已经在评论中添加并解释过了。

但是你应该知道检验质数的最短方法是检验n%x==0直到x<=square_root(n)。

首先,您不必检查n-1之前的所有数字的模量:检查sqrt(n)之前的模量就足够了。其次,如果要检查的下一个除数大于sqrt(n),则应该从函数返回0。以下是修正后的Remainder函数。

int Remainder(int n, int x)
{
    int q = n%x;
    if (q == 0)
        return 1;
    else
    {
        if(x+1 > std::sqrt(n)) return 0;
        else return Remainder(n, x + 1);
    }
}

最后,最好将mainAskern的类型由float改为int, Asker的返回类型也改为int

这不是一个关于质数检查器对焦问题的详尽列表-只是一种快速修复它的方法。从本质上讲,这样的素数检查器不应该使用递归—只迭代从2到sqrt(n)的所有可能的因数会更简洁。