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

นับตัวเลข N หลักที่เป็นไปได้ที่ตรงตามเงื่อนไขใน C++


ในบทช่วยสอนนี้ เราจะอภิบายโปรแกรมเพื่อหาจำนวนตัวเลข N หลักที่เป็นไปได้ที่ตรงตามเงื่อนไขที่กำหนด

สำหรับเรื่องนี้ เราจะได้รับจำนวนเต็ม งานของเราคือตรวจสอบว่าตัวเลขใดที่มี N หลักที่ทำให้

Number + Reverse(Number) = 10^N - 1

ตัวอย่าง

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

// returning the count of numbers
string count_num(int N) {
    if (N % 2 == 1)
        return "0";
    string result = "9";
    for (int i = 1; i <= N / 2 - 1; i++)
        result += "0";
    return result;
}

int main() {
    int N = 4;
    cout << count_num(N);
    return 0;
}

เอาต์พุต

ในบทช่วยสอนนี้ เราจะอภิบายโปรแกรมเพื่อหาจำนวนกลุ่มที่เป็นไปได้ขนาด 2 หรือ 3 ที่มีผลรวมเป็นพหุคูณของ 3

ในบทช่วยสอนนี้ เราจะอภิบายโปรแกรมเพื่อหาจำนวนกลุ่มที่เป็นไปได้ขนาด 2 หรือ 3 ที่มีผลรวมเป็นพหุคูณของ 3

ตัวอย่าง

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

// returning count of pairs of 2 or 3
int count_groups(int arr[], int n) {
    int c[3] = {0}, i;
    int res = 0;
    for (i = 0; i < n; i++)
        c[arr[i] % 3]++;
    res += ((c[0] * (c[0] - 1)) >> 1);
    res += c[1] * c[2];
    res += (c[0] * (c[0] - 1) * (c[0] - 2)) / 6;
    res += (c[1] * (c[1] - 1) * (c[1] - 2)) / 6;
    res += ((c[2] * (c[2] - 1) * (c[2] - 2)) / 6);
    res += c[0] * c[1] * c[2];
    return res;
}

int main() {
    int arr[] = {3, 6, 7, 2, 9};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Required number of groups are " << count_groups(arr, n) << endl;
    return 0;
}

เอาต์พุต

Required number of groups are 8