檢查某個數字是否能被其自身數字整除的 C 語言程式
給定一個數字 n,任務是查詢該數字中的任意數字是否能完全整除該數字。比如,給定數字 128625 是可以被 5 整除的,而數字中也包含 5。
示例
Input: 53142 Output: yes Explanation: This number is divisible by 1, 2 and 3 which are the digits of the number Input: 223 Output: No Explanation: The number is not divisible by either 2 or 3
以下為我們使用的方法 −
- 我們從個位開始,並獲取個位數字。
- 檢查該數字是否可整除
- 用 10 除以該數字
- 在數字變為 0 之前轉到步驟 1
演算法
Start
In function int divisible(long long int n)
Step 1-> Declare and initialize temp = n
Step 2 -> Loop while n {
Set k as n % 10
If temp % k == 0 then,
Return 1
Set n = n/ 10
End loop
Return 0
In Function int main()
Step 1-> Declare and initialize n = 654123
Step 2-> If (divisible(n)) then,
Print "Yes”
Step 3-> Else
Print "No”示例
#include <stdio.h>
int divisible(long long int n) {
long long int temp = n;
// check if any of digit divides n
while (n) {
int k = n % 10;
if (temp % k == 0)
return 1;
n /= 10;
}
return 0;
}
int main() {
long long int n = 654123;
if (divisible(n)) {
printf("Yes
");
}
else
printf("No
");
return 0;
}輸出
如果執行以上程式碼,將生成以下輸出 −
Yes
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP