開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Xcode - Apple
- Windows 10 Pro (OS)
- Visual Studio (コンパイラー)
- Visual Studio Code (Text Editor)
- C++17 (プログラミング言語)
Modern C++チャレンジ ―C++17プログラミング力を鍛える100問 (Marius Bancila(著)、島 敏博(監修)、黒川 利明(翻訳)、オライリージャパン)の1章(数学の問題)、問題9(素因数分解)の解答を求めてみる。
コード
#include <iostream> #include <cmath> bool is_prime(size_t n) { if (n < 2) { return false; } if (n <= 3) { return true; } for (size_t i = 4; i <= n / 2; i++) { if (n % i == 0) { return false; } } return true; } int main() { for (size_t i = 2; i < 101; i++) { size_t n = i; std::cout << n << " = "; for (size_t p = 2; p <= n; p++) { if (is_prime(p)) { size_t j = 0; while (n % p == 0) { j++; n /= p; if (n == 1) { break; } } if (j != 0) { if (j == 1) { std::cout << p; } else { std::cout << p << "^" << j; } if (n != 1) { std::cout << "・"; } } } } std::cout << std::endl; } }
入出力結果(cmd(コマンドプロンプト)、Terminal)
Active code page: 65001 C:\Users\...>cl /O2 sample9.cpp && sample9.exe Microsoft(R) C/C++ Optimizing Compiler Version 19.16.27027.1 for x64 Copyright (C) Microsoft Corporation. All rights reserved. sample9.cpp C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\xlocale(319): warning C4530: C++ 例外処理を使っていますが、アンワインド セマンティクスは有効にはなりません。/EHsc を指定してください。 Microsoft (R) Incremental Linker Version 14.16.27027.1 Copyright (C) Microsoft Corporation. All rights reserved. /out:sample9.exe sample9.obj 2 = 2 3 = 3 4 = 2^2 5 = 5 6 = 2・3 7 = 7 8 = 2^3 9 = 3^2 10 = 2・5 11 = 11 12 = 2^2・3 13 = 13 14 = 2・7 15 = 3・5 16 = 2^4 17 = 17 18 = 2・3^2 19 = 19 20 = 2^2・5 21 = 3・7 22 = 2・11 23 = 23 24 = 2^3・3 25 = 5^2 26 = 2・13 27 = 3^3 28 = 2^2・7 29 = 29 30 = 2・3・5 31 = 31 32 = 2^5 33 = 3・11 34 = 2・17 35 = 5・7 36 = 2^2・3^2 37 = 37 38 = 2・19 39 = 3・13 40 = 2^3・5 41 = 41 42 = 2・3・7 43 = 43 44 = 2^2・11 45 = 3^2・5 46 = 2・23 47 = 47 48 = 2^4・3 49 = 7^2 50 = 2・5^2 51 = 3・17 52 = 2^2・13 53 = 53 54 = 2・3^3 55 = 5・11 56 = 2^3・7 57 = 3・19 58 = 2・29 59 = 59 60 = 2^2・3・5 61 = 61 62 = 2・31 63 = 3^2・7 64 = 2^6 65 = 5・13 66 = 2・3・11 67 = 67 68 = 2^2・17 69 = 3・23 70 = 2・5・7 71 = 71 72 = 2^3・3^2 73 = 73 74 = 2・37 75 = 3・5^2 76 = 2^2・19 77 = 7・11 78 = 2・3・13 79 = 79 80 = 2^4・5 81 = 3^4 82 = 2・41 83 = 83 84 = 2^2・3・7 85 = 5・17 86 = 2・43 87 = 3・29 88 = 2^3・11 89 = 89 90 = 2・3^2・5 91 = 7・13 92 = 2^2・23 93 = 3・31 94 = 2・47 95 = 5・19 96 = 2^5・3 97 = 97 98 = 2・7^2 99 = 3^2・11 100 = 2^2・5^2 C:\Users\...>
0 コメント:
コメントを投稿