用 C++ 計數能被 2 到 10 之間所有數字整除的數字
給定一個數字,例如 num,任務是計算 1 到 num 範圍內能被 2、3、4、5、6、7、8、9 和 10 整除的數字個數。
輸入 − int num = 10000
輸出 − 能被 2 到 10 之間所有數字整除的數字個數為:3
解釋 − 從 1 到 10000 中,有 3 個數字能被從 2 到 10 的所有數字整除,它們是:
2520-: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 18, 20, 21, 24, 28, 30, 35, 36, 40, 42, 45, 56, 60, 63, 70, 72, 84, 90, 105, 120, 126, 140, 168, 180, 210, 252, 280, 315, 360, 420, 504, 630, 840, 1260, 2520. 5040-: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 28, 30, 35, 36, 40, 42, 45, 48, 56, 60, 63, 70, 72, 80, 84, 90, 105, 112, 120, 126, 140, 144, 168, 180, 210, 240, 252, 280, 315, 336, 360, 420, 504, 560, 630, 720, 840, 1008, 1260, 1680, 2520, 5040 7560-: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 18, 20, 21, 24, 27, 28, 30, 35, 36, 40, 42, 45, 54, 56, 60, 63, 70, 72, 84, 90, 105, 108, 120, 126, 135, 140, 168, 180, 189, 210, 216, 252, 270, 280, 315, 360, 378, 420, 504, 540, 630, 756, 840, 945, 1080, 1260, 1512, 1890, 2520, 3780.
輸入 − int num = 20000
輸出 − 能被 2 到 10 之間所有數字整除的數字個數為:6
解釋 − 從 1 到 20000 中,有 6 個數字能被從 2 到 10 的所有數字整除,它們是 − 2520, 5040, 7560, 10080, 12600, 15120,
下面程式中使用的方案如下:
解決這個問題有多種方法,即樸素方法和高效方法。讓我們首先看看**樸素方法**。
輸入數字,例如 num
建立一個數組,並將 2 到 10 之間的數字儲存到長度為 9 的整數陣列中。
使用兩個臨時變數:count 用於儲存數字總數,flag 用於檢查數字是否可被整除。
從 i=1 到 num 開始迴圈
在迴圈內,將 num 設定為 i,並將索引設定為 0
直到索引小於 9(即陣列大小)時開始 while 迴圈
檢查 IF num % arr[index++] == 0,則將 flag 設定為 1,否則將 flag 設定為 0
檢查 IF flag 為 1,則將 count 加 1
返回 count
列印結果。
高效方法
我們可以看到,能被 2 到 10 的所有數字整除的數字具有規律。
能被 2 到 10 的所有數字整除的最小數字是 2520
5 * 7 * 8 * 9 = 2520(n = 1) 5 * 7 * 8 * 9 * 2 = 5040(n = 2) 5 * 7 * 8 * 9 * 3 = 7560(n = 3) . .
我們可以看到,2520 是所有能被 2、3、4、5、6、7、8、9、10 整除的數字的公因子。因此,如果我們將給定數字除以 2520,我們將得到結果。
程式碼 1(樸素方法)
示例
#include <bits/stdc++.h>
using namespace std;
int count(int num){
int count = 0;
int flag=0;
int index=0;
int arr[9] = {2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 1; i <= num; i++){
int num = i;
index=0;
while(index<9){
if(num % arr[index++] == 0){
flag=1;
}
else{
flag=0;
break;
}
}
if (flag == 1){
count++;
}
}
return count;
}
int main(){
int num = 10000;
cout<<"Count numbers which are divisible by all the numbers from 2 to 10 are: "<<count(num);
return 0;
}輸出
如果執行上面的程式碼,它將生成以下輸出:
Count numbers which are divisible by all the numbers from 2 to 10 are: 3
程式碼 2(高效方法)
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
int num = 10000;
int count = num / 2520;
cout<<"Count numbers which are divisible by all the numbers from 2 to 10 are: "<<count;
return 0;
}輸出
如果執行上面的程式碼,它將生成以下輸出:
Count numbers which are divisible by all the numbers from 2 to 10 are: 3
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP