C++ 递归检查数字是否为素数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5450876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
recursively check if number is a prime
提问by Marijus
I'm trying to check whether the number is a prime(by dividing it by all numbers below n). Here's my attempt :
我正在尝试检查该数字是否为素数(通过将其除以 n 以下的所有数字)。这是我的尝试:
bool isPrime(int n, int d){
if (d == 1)
return true;
else{
if (n % d == 0){
return false;
}
else
return (n,d-1);
}
}
n - the number to check whether it is prime. d - number below n, when calling the function n-1.
n - 检查它是否为素数的数字。d - 当调用函数 n-1 时,小于 n 的数字。
Please help me figure out what am I doing wrong.
请帮我弄清楚我做错了什么。
回答by GWW
You aren't recursively calling your function. return (n,d-1);
should be return isPrime(n,d-1);
你不是递归调用你的函数。 return (n,d-1);
应该return isPrime(n,d-1);
回答by Vlad
Please don't write this in such a way! For more or less normal input, recursive approach will eat all the stack up! Just go for the old good iterative way.
请不要这样写!对于或多或少的正常输入,递归方法会吃掉所有的堆栈!只需采用旧的良好迭代方式即可。
Of course, the brute force solution is not the fastest one. You could try Eratosthenes' sieve, or some of numerous more advanced tests.
当然,蛮力解决方案并不是最快的解决方案。你可以试试Eratosthenes 的筛子,或者一些更高级的测试。
回答by Shubham Godara
You just need to include condition for checking 1 if it is prime or not.
您只需要包含检查 1 是否为素数的条件。
bool isPrime(int n, int d)
{
if(n<2)
return 0;
if(d == 1)
return true;
else
{
if(n % d == 0)
return false;
else
return isPrime(n, d - 1);
}
}
回答by Baivab Dash
#include<iostream>
using namespace std;
bool findPrime(int x,int y);
int main()
{int n;
cout<<"enter the number to be checked \n";
cin>>n;
int x=findPrime(n,n-1);
if(x==1)
cout<<"its a prime number";
else
cout<<"its not prime";
}
bool findPrime(int x,int y)
{
if(x%y==0&&y!=1)
{
return false;
}
else{
if(y==1)
return true;
else
return findPrime(x,y-1);
}
}