Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับจำนวน m หลักที่หารด้วย n ลงตัว ใน C++

ได้รับจำนวนเต็ม m และ n ต้องการนับจำนวน m หลักที่หารด้วย n ลงตัว

ตัวอย่าง

อินพุต: m = 2, n = 9

เอาต์พุต: 10

คำอธิบาย: เลข 2 หลัก (10-99) ที่หาร 9 ลงตัว: 18, 27, 36, 45, 54, 63, 72, 81, 90, 99

อินพุต: m = 3, n = 300

เอาต์พุต: 3 (300, 600, 900)

แนวทาง

  • หาเลข m-1 หลักมากที่สุด (num1) และ m หลักมากที่สุด (num2)
  • ช่วงที่ต้องการคือ [num1+1, num2]
  • วนนับในช่วงนี้ว่าตัวไหนหาร n ลงตัว

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

int findCount(int n, int L, int R) {
    int count = 0;
    for (int i = L; i <= R; i++) {
        if (i % n == 0) count++;
    }
    return count;
}

int main() {
    int M = 2, N = 9;
    int num1 = 0;
    for (int i = 0; i < (M - 1); i++) num1 = (num1 * 10) + 9;
    int num2 = 0;
    for (int i = 0; i < M; i++) num2 = (num2 * 10) + 9;
    cout << "Count of M digit no.s divisible by N: " << findCount(N, num1 + 1, num2);
    return 0;
}

ผลลัพธ์

Count of M digit no.s divisible by N: 11