C++中計算區間內能被所有非零數字整除的數字


我們提供兩個數字START和END來定義一個數字範圍。目標是找到[START,END]範圍內所有能被其所有非零數字整除的數字。我們將透過遍歷從START到END的數字來實現這一點,對於每個數字,我們將使用while迴圈檢查該數字是否能被所有非零數字整除。如果是,則計數器加1。

讓我們透過例子來理解。

輸入 

START=10 END=20

輸出 

Numbers that are divisible by all its non-zero digits: 14

解釋 

Numbers 10, 11, 12, 15, 20 are divisible by all their non-zero digits.

輸入 

START=100 END=200

輸出 

Numbers that are divisible by all its non-zero digits: 25

解釋 

This is list of numbers divisible by all non-zero digits : 100 101 102 104 105 110 111 112 115 120 122 124 126 128 132 135 140 144 150 155 162 168 175 184 200

下面程式中使用的方法如下

  • 我們將整數START和END作為範圍變數。

  • 函式divisiblebyDigits(int start, int end)接收範圍變數並返回能被所有非零數字整除的數字個數。

  • 將初始變數count設定為0,表示此類數字的個數。

  • 將變數flag設定為0。

  • 使用for迴圈遍歷數字範圍。i=start到i=end。

  • 現在,對於每個數字num=i,使用while迴圈檢查數字是否>0。

  • 計算digit=num%10。如果digit>0且i%digit==0,則設定flag=1。否則,flag=0並中斷迴圈。將num=num/10以檢查下一個數字。

  • 如果所有非零數字都能完全整除i,則flag為1。計數器加1。

  • 在所有迴圈結束時,count將包含能被非零數字整除的總數。

  • 返回count作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int divisiblebyDigits(int start, int end){
   int count = 0;
   int flag=0;
   for (int i = start; i <= end; i++){
      int num=i;
      while(num>0){
         int digit=num%10;
         if(digit>0){
            if(i%digit==0)
               { flag=1; } //set flag
            else{
               flag=0; //un-set flag
               break;
            }
         }
         num=num/10;
      }
      if(flag==1) //divisible by all non-zero digits {
         count++;
         //cout<<i<<" ";
      }
   }
   return count;
}
int main(){
   int START = 10, END = 50;
   cout <<"Numbers that are divisible by all its non-zero digits: "<< divisiblebyDigits(START,END);
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Numbers that are divisible by all its non-zero digits: 14

更新於:2020年10月31日

145 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告