একটি ইন্টিজার রেঞ্জ, একটি ভেরিয়েবল m (ভাজক) এবং একটি ভেরিয়েবল d (ডিজিট) দেওয়া আছে। কাজ হল রেঞ্জে এমন সংখ্যাগুলোর সংখ্যা বের করা যারা m দিয়ে বিভাজ্য এবং যাদের ইভেন পজিশনে ডিজিট d রয়েছে।
উদাহরণ
ইনপুট - int start = 20, end = 50, d = 8, m = 4
আউটপুট - রেঞ্জে m দিয়ে বিভাজ্য এবং ইভেন পজিশনে ডিজিট d থাকা সংখ্যা: 2
ব্যাখ্যা - রেঞ্জ ২০ থেকে ৫০। ডিজিট ৮ থাকা সংখ্যা: ২৮, ৩৮, ৪৮ (৮ ইভেন পজিশনে)। এদের মধ্যে ২৪ এবং ৪৮ হল ৪ দিয়ে বিভাজ্য। তাই কাউন্ট ২।
ইনপুট - int start = 10, end = 100, d = 6, m = 2
আউটপুট - রেঞ্জে m দিয়ে বিভাজ্য এবং ইভেন পজিশনে ডিজিট d থাকা সংখ্যা: 8
ব্যাখ্যা - রেঞ্জ ১০ থেকে ১০০। ডিজিট ৬ ইভেন পজিশনে থাকা সংখ্যা: ১৬, ২৬, ৩৬, ৪৬, ৫৬, ৬৬, ৭৬, ৮৬, ৯৬ (৬ এবং ৬৬ বাদে কারণ ৬ অড পজিশনে)। এসব ২ দিয়ে বিভাজ্য। তাই কাউন্ট ৮।
প্রোগ্রামে ব্যবহৃত পদ্ধতি
- রেঞ্জ, d, m ইনপুট নিয়ে ফাংশনে পাস করুন।
- ভেক্টর
vecডিক্লেয়ার করুন। - হোয়াইল লুপে
val-এর ডিজিটগুলোvec-এ পুশ করুন এবং রিভার্স করুন। - অ্যারে -1 দিয়ে ইনিশিয়ালাইজ করুন (
memset)। set_total(0, 0, 0, vec)রিটার্ন করুন।set_totalফাংশনে:- যদি
place == vec.size()হয় তবেtemp == 0হলে ১ রিটার্ন করুন অন্যথায় ০। - যদি
arr[place][temp][val] != -1হয় তবে সেটি রিটার্ন করুন। - যদি
place % 2 == 1হয় (অড পজিশন) তবে ইভেন পজিশন চেক করুন। - রিকার্সিভ কল দিয়ে কাউন্ট হিসাব করুন।
- যদি
উদাহরণ কোড
#include <bits/stdc++.h>
using namespace std;
int arr[20][20][2];
int d, m;
int set_total(int place, int temp, int val, vector<int> vec) {
if (place == vec.size()) {
if (temp == 0) return 1;
return 0;
}
if (arr[place][temp][val] != -1) {
return arr[place][temp][val];
}
if (place % 2) {
if (val == 0) {
if (d > vec[place]) return 0;
}
int temp_2 = val;
if (d < vec[place]) temp_2 = 1;
int temp_3 = set_total(place + 1, (10 * temp + d) % m, temp_2, vec);
return arr[place][temp][val] = temp_3;
}
int count = 0;
int set_limit = (val ? 9 : vec[place]);
for (int i = 0; i <= set_limit; i++) {
if (i == d) continue;
int temp_2 = val;
if (i < vec[place]) temp_2 = 1;
count += set_total(place + 1, (10 * temp + i) % m, temp_2, vec);
}
return arr[place][temp][val] = count;
}
int divisible(int val) {
vector<int> vec;
while (val) {
vec.push_back(val % 10);
val = val / 10;
}
reverse(vec.begin(), vec.end());
memset(arr, -1, sizeof(arr));
return set_total(0, 0, 0, vec);
}
int main() {
int start = 20, end = 50;
d = 8, m = 4;
int count = divisible(end) - divisible(start);
cout << "Count of Numbers in a Range divisible by m and having digit d in even positions are: " << count;
return 0;
}
উপরের কোড রান করলে নিচের আউটপুটটি পাওয়া যাবে:
আউটপুট
Count of Numbers in a Range divisible by m and having digit d in even positions are: 2