C語言程式檢查強數
給定一個數字'n',我們需要檢查給定的數字是否為強數。
強數是一個數字,其所有數字的階乘之和等於數字'n'。階乘是指當我們找到包括該數字在內的該數字下方所有數字的乘積時,並用!(感嘆號)表示,例如:4!= 4x3x2x1 = 24。
因此,要查詢一個數字是否為強數,我們必須選擇該數字的每個數字,例如數字是 145,那麼我們必須選擇 1、4 和 5,現在我們將找到每個數字的階乘,即 1!= 1、4!= 24、5!= 120。
現在我們將 1 + 24 + 120 相加,因此我們得到 145,這與給定的輸入完全相同,因此我們可以說該數字是強數。
示例
Input: n = 124 Output: No it is not a strong number Explanation: 1! + 2! + 4! = 27 which is not equal to n i.e, 124 Input: n = 145 Output: Yes it is a strong number Explanation: 1! + 4! + 5! = 145
下面使用的解決問題的方法如下 −
我們將 −
- 從個位數開始取每個數字並找到它的階乘。
- 我們將新增每個數字的這些階乘。
- 將結果與原始數字進行比較,如果它們相等,則該數字為強數;否則該數字不是強數。
演算法
START In Function int factorial(int r) Step1 -> Initialize int fact and set as 1 Step2-> Loop while r>1 Set fact as fact * r Decremnet r by 1 End Loop Step 3-> Return fact End Function factorial In Function int check(int n) Step 1-> Initialize int temp, rem and result, set result as 0 Step 2-> Set temp as n Step 3-> Loop while temp Set rem as temp % 10 Set result as result + factorial(rem) Set temp as temp/10 End loop Step 4-> If result == n then, Return 1 Step 5-> Else Return 0 End function check In main(int argc, char const *argv[]) Step 1-> Initialise and set n as 145 Step 2->If check(n) is valid then, Print "Yes it is a strong number” Step 3-> Else Print "no it is not a strong number” STOP
示例
#include <stdio.h>
int factorial(int r) {
int fact = 1;
while(r>1) {
fact = fact * r;
r--;
}
return fact;
}
int check(int n) {
int temp, rem, result = 0;
temp = n;
while(temp) {
rem = temp % 10;
result = result + factorial(rem);
temp = temp/10;
}
if (result == n)
return 1;
else
return 0;
}
int main(int argc, char const *argv[]) {
int n = 145;
if (check(n))
printf("Yes it is a strong number
");
else
printf("no it is not a strong number
");
return 0;
}如果執行以上程式碼,它將生成以下輸出 −
Yes it is a strong number
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP