0
재귀 함수를 사용하는 방법을 이해하려고하는데이 함수가 잘못된 이유를 알지 못합니다. Base Case 2에 있다고 생각하지만 이유를 모르겠습니다.재귀 소수 번호 함수 C++
#include <iostream>
using namespace std;
// Returns 0 if value is not prime, 1 if value is prime
int IsPrime(int testVal, int divVal)
{
// Base case 1: 0 and 1 are not prime, testVal is not prime
if(testVal == 0 || testVal == 1){
return 0;
}
// Base case 2: testVal only divisible by 1, testVal is prime
if(testVal/1 == testVal){
return 1;
}
// Recursive Case
// Check if testVal can be evenly divided by divVal
// Hint: use the % operator
if(testVal % divVal != 1){
IsPrime(testVal, divVal);
}
// If not, recursive call to isPrime with testVal and (divVal - 1)
return 0;
}
int main(){
int primeCheckVal = 0; // Value checked for prime
// Check primes for values 1 to 10
for (primeCheckVal = 1; primeCheckVal <= 10; ++primeCheckVal) {
if (IsPrime(primeCheckVal, (primeCheckVal - 1)) == 1) {
cout << primeCheckVal << " is prime." << endl;
}
else {
cout << primeCheckVal << " is not prime." << endl;
}
}
}
if (testVal/1 == testVal)을 사용하여 달성하려는 작업이 무엇인지 분명하지 않습니다. **로 나누어 진 모든 것이 true 일 것입니다. – Steve
디버거를 사용하여 코드를 단계별로 실행하는 방법을 배워야 할 수도 있습니다. 좋은 디버거를 사용하면 한 줄씩 프로그램을 실행하고 예상 한 곳에서 벗어난 곳을 볼 수 있습니다. 프로그래밍을 할 때 필수적인 도구입니다. 추가 읽기 : [작은 프로그램을 디버깅하는 방법] (http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). 그렇게 함으로서'testVal'이나'divVal'을 절대 수정하지 않을 것입니다. – NathanOliver