#include #include #include using namespace std;

bool isHappy(int n) { vector visited; while (n != 1) { if (find(visited.begin(), visited.end(), n) != visited.end()) { return false; } visited.push_back(n); int sum = 0; while (n != 0) { int digit = n % 10; sum += pow(digit, 2); n /= 10; } n = sum; } return true; }

bool isPrime(int n) { if (n <= 1) { return false; } for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) { return false; } } return true; }

int main() { int A, B; cin >> A >> B;

bool hasHappy = false;
for (int i = A; i <= B; i++) {
    if (isHappy(i)) {
        int happiness = 0;
        for (int j = A; j <= B; j++) {
            if (isHappy(j) && j != i) {
                happiness++;
            }
        }
        if (isPrime(i)) {
            happiness *= 2;
        }
        cout << i << " " << happiness << endl;
        hasHappy = true;
    }
}
if (!hasHappy) {
    cout << "SAD" << endl;
}

return 0;

}

C++ 程序:找出给定区间内的特立独行的幸福数

原文地址: https://www.cveoy.top/t/topic/pCAz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录