Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
N’th Smart Number in C++
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.
The smart number series are
30, 42, 60, 66, 70, 78...
Algorithm
- Initialise the number N.
- Initialise the count to 0.
- Write a function that checks whether the given number is prime or not.
- 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.
- Check whether the current number is smart number or not using the prime number function.
- Increment the count by 1 when you find a smart number.
- Return the smart number when you count is equals to N.
Implementation
Following is the implementation of the above algorithm in C++
#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
Advertisements