N’th Smart Number in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the n-th smart number.

A smart number is a number that contains at least three distinct prime factors. You are given a number N. Find the n-th smart number.

Example

Let's see the steps to solve the problem.

  • Initialise the number N.
  • Initialise the count to 0.
  • Write a function that checks whether the number is smart or not
  • Write a loop that iterates from 30 as first smart number is 30.
    • Increment the count by 1 when you find a smart number.
    • Return the smart number when you count is equals to N.

Example

Let's see the code.

 Live Demo

#include<bits/stdc++.h>
using namespace std;
bool isPrime(int n) {
   if (n < 2) return false;
   for (int i = 2; i <= sqrt(n); i++) {
      if (n % i == 0) return false;
   }
   return true;
}
bool isSmartNumber(int n) {
   int count = 0;
   for (int i = 2; i < n; i++) {
      if (n % i == 0 && isPrime(i)) {
         count += 1;
      }
      if (count == 3) {
         return true;
      }
   }
return false;
}
int getNthSmartNumber(int n) {
   int i = 30, count = 0;
   while (true) {
      if (isSmartNumber(i)) {
         count += 1;
      }
      if (count == n) {
         return i;
      }
      i += 1;
   }
}
int main() {
   int N = 25;
   cout << getNthSmartNumber(N) << endl;
   return 0;
}

Output

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

174
raja
Published on 29-Jun-2021 09:47:32
Advertisements