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

โปรแกรม C++ เพื่อค้นหาตัวเลขที่มีตัวหารคี่ K ในช่วงที่กำหนด


ในปัญหานี้ เราได้รับค่าจำนวนเต็มสามค่า L, R และ k งานของเราคือการหาตัวเลขที่มีตัวหาร K ในช่วงที่กำหนด เราจะหาจำนวนตัวเลขในช่วง [L, R] ที่มีตัวหาร k อยู่พอดี เราจะนับ 1 และตัวเลขเป็นตัวหาร

มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน

อินพุต

a = 3, b = 10, k = 4

ผลลัพธ์

2

คำอธิบาย

Numbers with exactly 3 divisors within the range 3 to 10 are
6 : divisors = 1, 2, 3, 6 8 : divisors = 1, 2, 4, 8

แนวทางการแก้ปัญหา

วิธีแก้ปัญหาอย่างง่ายคือการนับตัวหาร k. ดังนั้น เราจะนับจำนวนตัวหารสำหรับตัวเลขทั้งหมดในช่วง และถ้าการนับตัวหารเป็น k เราจะบวก 1 เข้ากับจำนวนนับ

โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา

ตัวอย่าง

#include<bits/stdc++.h>
using namespace std;
int countDivisors(int n) {
   int divisors = 0;
   for (int i=1; i<=sqrt(n)+1; i++) {
      if (n%i==0) {
         divisors++;
         if (n/i != i)
            divisors ++;
      }
   }
   return divisors;
}
int countNumberKDivisors(int a,int b,int k) {
   int numberCount = 0;
   for (int i=a; i<=b; i++) {
      if (countDivisors(i) == k)
         numberCount++;
   }
   return numberCount;
}
int main() {
   int a = 3, b = 10, k = 4;
   cout<<"The count of numbers with "<<k<<" divisors is "<<countNumberKDivisors(a, b, k);
   return 0;
}

ผลลัพธ์

The count of numbers with 4 divisors is 2