Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตรวจสอบ Krishnamurthy Number ใน C++

ในบทความนี้จะตรวจสอบว่า Number เป็น Krishnamurthy Number หรือไม่ Krishnamurthy Number คือ Number ที่ผลรวม Factorial ของแต่ละ Digit เท่ากับ Number เดิม ตัวอย่าง 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 เป็น Krishnamurthy Number

ตรรกะ: หา Factorial แต่ละ Digit รวมกัน ถ้าเท่ากับ Number เดิม คือ Krishnamurthy Number

ตัวอย่างโค้ด C++

#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;
    }
    if(sum == temp) {
        return true;
    }
    return false;
}

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

ผลลัพธ์

145 is Krishnamurty Number