Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Kiểm tra số Krishnamurthy trong C++


Số Krishnamurthy (còn gọi là Strong number) là số bằng tổng giai thừa các chữ số của nó. Ví dụ 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145.

Cách làm: tách từng chữ số, tính giai thừa (đệ quy hoặc bảng tra), cộng dồn, so sánh với số gốc.

Ví dụ

#include <iostream>
#include <cmath>
using namespace std;

long factorial(int n){
    if(n <= 1) return 1;
    return n * factorial(n - 1);
}

bool isKrishnamurty(int number) {
    int temp = number;
    int sum = 0;
    while(number > 0){
        sum += factorial(number % 10);
        number /= 10;
    }
    return (sum == temp);
}

int main() {
    int n = 145;
    if(isKrishnamurty(n)){
        cout << n << " is Krishnamurty Number";
    } else {
        cout << n << " is not Krishnamurty Number";
    }
}

Kết quả

145 is Krishnamurty Number