Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active November 19, 2017 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/9afed026ef62388d399f5a0e5acd909b to your computer and use it in GitHub Desktop.
Save komasaru/9afed026ef62388d399f5a0e5acd909b to your computer and use it in GitHub Desktop.
C++ source code to judge prime number.
/*********************************************
* 素数判定
*********************************************/
#include <iostream> // for cout, cin
#include <math.h> // for sqrt
//#include <stdio.h> // for printf, scanf
using namespace std;
/*
* 計算クラス
*/
class Prime
{
// 宣言
int i, iLimit;
public:
// 素数判定
bool isPrime(int a);
};
/*
* 素数判定
*/
bool Prime::isPrime(int a)
{
// 1 は素数でない
if (a == 1) return false;
// 2 から √a を超えない整数までループ処理
iLimit = (int)sqrt(a);
for (i = 2; i <= iLimit; i++) {
// 途中割り切れたらブレーク
if (a % i == 0) break;
}
// 最後までループしきったら
// 約数がなかったということで素数と判定
if (i == iLimit + 1) {
return true;
} else {
return false;
}
}
/*
* メイン処理
*/
int main()
{
int iNum;
bool bPrime;
try
{
// 素数クラスインスタンス化
Prime objPrime;
while (1) {
// 自然数入力
cout << "自然数 ( 0 : 終了 ):";
cin >> iNum;
if (cin.fail()) break;
if (iNum < 1) break;
// 素数判定
bPrime = objPrime.isPrime(iNum);
if (bPrime) {
cout << iNum << " : 素数" << endl;
} else {
cout << iNum << " : 素数ではない" << endl;
}
}
}
catch (...) {
cout << "例外発生!" << endl;
return -1;
}
// 正常終了
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment