检查某个数字是否能被其自身数字整除的 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