इस समस्या में, हमें एक संख्या N दी जाती है। हमारा कार्य [1, n] की श्रेणी में सभी संख्याओं के भाजक की संख्या ज्ञात करना है।
समस्या को समझने के लिए एक उदाहरण लेते हैं,
Input : N = 7 Output : 1 2 2 3 2 4 2
समाधान दृष्टिकोण
समस्या का एक सरल समाधान 1 से N तक शुरू करना है और प्रत्येक संख्या के लिए भाजक की संख्या गिनें और उन्हें प्रिंट करें।
उदाहरण 1
हमारे समाधान की कार्यप्रणाली को दर्शाने के लिए कार्यक्रम
#include <iostream>
using namespace std;
int countDivisor(int N){
int count = 1;
for(int i = 2; i <= N; i++){
if(N%i == 0)
count++;
}
return count;
}
int main(){
int N = 8;
cout<<"The number of divisors of all numbers in the range are \t";
cout<<"1 ";
for(int i = 2; i <= N; i++){
cout<<countDivisor(i)<<" ";
}
return 0;
} आउटपुट
The number of divisors of all numbers in the range are 1 2 2 3 2 4 2 4
समस्या को हल करने के लिए एक अन्य दृष्टिकोण मूल्यों की वृद्धि का उपयोग कर रहा है। इसके लिए, हम आकार की एक सरणी (N+1) बनाएंगे। फिर, 1 से N तक, हम प्रत्येक मान i की जांच करेंगे, हम n से कम i के सभी गुणकों के लिए सरणी मान बढ़ाएंगे।
उदाहरण 2
हमारे समाधान की कार्यप्रणाली को दर्शाने के लिए कार्यक्रम,
#include <iostream>
using namespace std;
void countDivisors(int N){
int arr[N+1];
for(int i = 0; i <= N; i++)
arr[i] = 1;
for (int i = 2; i <= N; i++) {
for (int j = 1; j * i <= N; j++)
arr[i * j]++;
}
for (int i = 1; i <= N; i++)
cout<<arr[i]<<" ";
}
int main(){
int N = 8;
cout<<"The number of divisors of all numbers in the range are \t"; countDivisors(N);
return 0;
} आउटपुट
The number of divisors of all numbers in the range are 1 2 2 3 2 4 2 4