使用 C++ 統計 1 到 N 範圍內能被 X 整除但不能被 Y 整除的數字個數


給定一個數字 N,目標是找到在範圍 [1,N] 內能被 X 整除但不能被 Y 整除的數字。

讓我們透過示例來理解。

輸入 

N=20 X=5 Y=20

輸出 

Numbers from 1 to N divisible by X not Y: 2

解釋 

Only 5 and 15 are divisible by 5 and not 10.

輸入 

N=20 X=4 Y=7

輸出 

Numbers from 1 to N divisible by X not Y: 5

解釋 

Numbers 4, 8, 12, 16 and 20 are divisible by 4 and not 7.

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

  • 我們獲取一個整數 N。

  • 函式 divisibleXY(int x, int y, int n) 返回 1 到 N 範圍內能被 X 整除但不能被 Y 整除的數字個數。

  • 將初始變數 count 初始化為 0,用於儲存此類數字的個數。

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

  • 現在,對於每個數字 i,檢查 ( i%x==0 && i%y!=0 ) 是否成立,如果成立則遞增 count。

  • 返回 count 作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int divisibleXY(int x, int y, int n){
   int count = 0;
   for (int i = 1; i <= n; i++) {
      if(i%x==0 && i%y!=0 )
         { count++; }
   }
   return count;
}
int main(){
   int N = 100;
   int X=6, Y=8;
   cout <<"Numbers from 1 to N which are divisible by X and not Y: "<< divisibleXY(X,Y,N);
   return 0;
}

輸出

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

Numbers from 1 to N which are divisible by X and not Y: 12

更新時間: 2020-10-31

552 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告