首頁 > 後端開發 > C++ > 主體

C程式檢查一個數字是否可被其各位數字之和整除

王林
發布: 2023-08-30 16:05:08
轉載
1529 人瀏覽過

C程式檢查一個數字是否可被其各位數字之和整除

給定一個數字n,我們需要檢查其各位數字總和是否能整除n。為了找出答案,我們需要將所有數字從個位開始相加,然後用最終的和去除以該數字。

例如我們有一個數字"521",我們需要找出其各位數字之和,即"5 2 1 = 8",但是521不能被8整除,餘數不為0。

再舉個例子,"60",其各位數字之和為"6 0 = 6",6能夠整除60,餘數為0。

範例

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
登入後複製

下面使用的方法如下:

為了解決這個問題,我們需要從輸入中取得每個數字,並計算每個數字的和,然後檢查它是否能整除這個數字。

  • 取得輸入
  • 從個位元開始取得每個數字,並將其加到初始值為零的總和變數中
  • 用數字的總和除以輸入
  • 返回結果

演算法

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</p><p>");
   else
      printf("no</p><p>");
      return 0;
}
登入後複製

輸出

如果執行上述程式碼,將會產生以下輸出−

No
登入後複製

以上是C程式檢查一個數字是否可被其各位數字之和整除的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!