// C++ 14 寫法(因為zerojudge僅支援 C++ 14) #include<iostream> #include<algorithm>
usingnamespace std;
intmain(){ ios::sync_with_stdio(false); cin.tie(nullptr); int x, y; cin >> x >> y; cout << __gcd(x, y); return0; }
輾轉相除法寫法(for迴圈):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<iostream>
usingnamespace std;
intmain(){ ios::sync_with_stdio(false); cin.tie(nullptr); int x, y, temp; cin >> x >> y; while (y != 0) { // (a, b) = (b, a % b) temp = y; y = x % y; x = temp; } cout << x; }
遞迴寫法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
usingnamespace std;
intgcd(int x, int y){ if (x % y == 0) return y; returngcd(y, x % y); }
intmain(){ ios::sync_with_stdio(false); cin.tie(nullptr); int x, y; cin >> x >> y; cout << gcd(x, y); return0; }
boolisArmstrong(int num){ // 判斷是否為阿姆斯壯數 int original = num; // 保留原始數字(比較用) int sum = 0; int digits = 0; int temp = num; while (temp > 0) { // 算有幾位數 digits++; temp /= 10; } temp = num; while (temp > 0) { // 計算每位數的 n 次方總和 int digit = temp % 10; sum += pow(digit, digits); temp /= 10; } return sum == original; }
intmain(){ int n, m; cin >> n >> m; vector<int> armstrongNumbers; for (int i = n; i <= m; ++i) { if (isArmstrong(i)) { armstrongNumbers.push_back(i); } } if (armstrongNumbers.empty()) { cout << "none"; } else { // size_t 就是 unsigned int for (size_t i = 0; i < armstrongNumbers.size(); ++i) { cout << armstrongNumbers[i]; if (i != armstrongNumbers.size() - 1) { cout << " "; } } } return0; }