เราได้รับตัวเลขสามตัว A,B และ M A และ B กำหนดช่วง [A,B] ของตัวเลข เป้าหมายคือการนับตัวเลขระหว่าง A และ B ที่หารด้วย M ลงตัว
เราจะเริ่มจาก i=A จนถึงทวีคูณแรกของ M การนับการเพิ่มขึ้นหาก i%M=0 ตอนนี้เพิ่ม i จนถึง i<=จำนวนแบนด์ที่เพิ่มขึ้น
มาทำความเข้าใจกับตัวอย่างกัน
อินพุต
A=11,B=20, M=5
ผลลัพธ์
Count of numbers divisible by M in given range: 2
คำอธิบาย
15 และ 20 เป็นเพียงตัวเลขที่หารด้วย 5 ลงตัวและอยู่ในช่วง [11,20]
อินพุต
A=20, B=50, M=11
ผลลัพธ์
Count of numbers divisible by M in given range: 3
คำอธิบาย
22,33,44 เป็นเพียงตัวเลขที่หารด้วย 11 ลงตัวและอยู่ในช่วง [20,50]
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้
- เราใช้ A,B และ M เป็นจำนวนเต็ม
- ฟังก์ชันหารด้วย M (int a, int b, int m) รับ A,B และ M เป็นพารามิเตอร์และคืนค่าจำนวนตัวเลขระหว่าง A และ B ที่หารด้วย M ลงตัว
- นับเริ่มต้นเป็น 0
- ใช้ลูป เริ่มจาก i=A ถึง i=B เพิ่ม i โดย 1.
- ถ้า i%m=0, นับการเพิ่มขึ้น
- ในตอนท้าย นับเป็นตัวเลขระหว่าง A และ B ที่หารด้วย m ลงตัว
- ผลตอบแทนนับเป็นผลลัพธ์
ตัวอย่าง
// Program to count the numbers divisible by
// M in a given range
#include <bits/stdc++.h>
using namespace std;
int divisiblebyM(int a, int b, int m){
int count = 0;
// Running a loop from A to B and check
// if a number is divisible by M.
for (int i = a; i <= b;i++ ){
if (i % m == 0){
count++;
}
}
return count;
}
int main(){
// A and B define the range, M is the dividend
int A = 3, B = 15, M = 4;
cout<<"Numbers divisible by M in given range:"<<divisiblebyM(A, B, M) << endl;
return 0;
} ผลลัพธ์
Numbers divisible by M in given range:3