 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count all the numbers in a range with smallest factor as K in C++
In this tutorial, we will be discussing a program to find the numbers in a range with the smallest factor as K.
For this we will be provided with a range [a,b]. Our task is to count the numbers in the given range who have their smallest factor as K.
Example
#include <bits/stdc++.h> using namespace std; //checking if K is a prime bool if_prime(int k){    if (k <= 1)       return false;    for (int i = 2; i < k; i++)    if (k % i == 0)       return false;       return true; } //checking if any number is divisible by K int check(int num, int k){    int flag = 1;    for (int i = 2; i < k; i++) {       if (num % i == 0)          flag = 0;    }    if (flag == 1) {       if (num % k == 0)          return 1;       else          return 0;    }    else       return 0; } //counting the possible numbers int findCount(int a, int b, int k){    int count = 0;    if (!if_prime(k))       return 0;    else {       int ans;       for (int i = a; i <= b; i++) {          ans = check(i, k);          if (ans == 1)             count++;          else             continue;       }    }    return count; } int main(){    int a = 2020, b = 6300, k = 29;    cout << findCount(a, b, k);    return 0; }  Output
28
Advertisements
 