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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP