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

 Live Demo

#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
Updated on: 2020-02-17T10:20:56+05:30

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements