C语言程序:检查数字是否能被其各位数字之和整除


给定一个数字n,我们必须检查其各位数字之和是否能整除n。为此,我们需要从个位开始将所有数字相加,然后用最终的和来除以该数字。

例如,我们有一个数字“521”,其各位数字之和为“5 + 2 + 1 = 8”,但521不能被8整除。

再举一个例子,“60”,其中“6+0 = 6”,6能整除60,并且没有余数。

示例

Input: 55
Output: No
Explanation: 5+5 = 10; 55 not divisible by 10
Input: 12
Output: Yes
Explanation: 1+2 = 3; 12 is divisible by 3

下面使用的方案如下:

为了解决这个问题,我们必须从输入中获取每个数字,并找到数字的每位数字之和,然后检查它是否能整除该数字。

  • 获取输入
  • 使用从个位开始获取每个数字,并将其添加到初始值为零的sum变量中
  • 用数字的和来除以输入。
  • 返回结果。

算法

In function int isDivisible(long int num)
   Step 1-> Declare and initialize temp = num, sum = 0
   Step 2-> Loop While num
      Declare and initialize k as num % 10
   Set sum as sum + k
      Set num as num / 10
   End Loop
   Step 3-> If temp % sum == 0 then,
      Return 1
   Step 4-> Return 0
      End function
In main()
   Step 1-> Declare and initialize num as 55
   Step 2-> If isDivisible(num) then,
      Print "yes "
   Step 3-> Else
Print "no "

示例

 在线演示

#include <stdio.h>
// This function will check
// whether the given number is divisible
// by sum of its digits
int isDivisible(long int num) {
   long int temp = num;
   // Find sum of digits
   int sum = 0;
   while (num) {
      int k = num % 10;
      sum = sum + k;
      num = num / 10;
   }
   // check if sum of digits divides num
   if (temp % sum == 0)
      return 1;
      return 0;
}
int main() {
   long int num = 55;
   if(isDivisible(num))
      printf("yes
");    else       printf("no
");       return 0; }

输出

如果运行以上代码,它将生成以下输出:

No

更新于:2019年10月21日

2K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.