Last active
February 7, 2022 03:34
-
-
Save yusuketanabe/66651740c783cde755e6edf473a12655 to your computer and use it in GitHub Desktop.
Recursive function memo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
// Auxiliary functions of is_prime | |
bool has_divisor(int N, int i) { | |
// Base | |
// 0ならば対象の整数がないまたは、i == Nなら自分(と1)以外約数が存在しない。 | |
if (i == N) return false; | |
// i~N-1までの範囲で約数が存在する。 | |
if (N % i == 0) return true; | |
// Recursive | |
return has_divisor(N, i+1); | |
} | |
bool is_prime(int N) { | |
if (N == 1) return false; // 素数じゃない | |
else if (N == 2) return true; // 素数 | |
// 2~N-1の範囲に約数がなければNは素数。 | |
else return !has_divisor(N, 2); | |
} | |
int main() { | |
std::cout << is_prime(0) << std::endl; | |
std::cout << is_prime(1) << std::endl; | |
std::cout << is_prime(2) << std::endl; | |
std::cout << is_prime(5) << std::endl; | |
std::cout << is_prime(13) << std::endl; | |
std::cout << is_prime(57) << std::endl; | |
} | |
/* output | |
0 | |
0 | |
1 | |
1 | |
1 | |
0 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment