k-Rough Number or k-Jagged Number in C++


In this tutorial, we are going to write a program that checks whether the given number is k-rough or k-jagged number or not.

The number whose smallest prime factor is greater than or equal to the given k, it is called k-rough or k-jagged number.

Let's see the steps to solve the problem.

  • Initialise the numbers n and k.
  • Find all the prime numbers that are factors of n and store them in a vector.
  • Get the first element from the vector and compare it with k to check whether n is k-rough or k-jagged number or not.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool isPrime(int n) {
   for (int i = 2; i * i <= n; i++) {
      if (n % i == 0) {
         return false;
      }
   }
   return true;
}
vector<int> getPrimes(int n) {
   vector<int> primes;
   for (int i = 2; i < n; i++) {
      if (n % i == 0 && isPrime(i)) {
         primes.push_back(i);
      }
   }
   return primes;
}
bool isRoughNumber(int n, int k) {
   vector<int> primes = getPrimes(n);
   return primes[0] >= k;
}
int main() {
   int n = 75, k = 3;
   if (isRoughNumber(n, k)) {
      cout << n << " is a " << k << " rough number" << endl;
   }else {
      cout << n << " is not a " << k << " rough number" << endl;
   }
   return 0;
}

Output

If you run the above program, then you will get the following result.

75 is a 3 rough number

Conclusion

You can avoid storing all the prime numbers in the vector. And find the first prime factor of n and compare it with k to get the desired output. Implement the idea which is similar to the above one with lesser space and time complexity.

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 09-Apr-2021

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements