
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
Frugal Number in C++
In this problem, we are given a positive integer N. Our task is to create a program to check whether the given number is a Frugal number or not.
FRUGAL NUMBER − A number whose number of digits is strictly greater than the number of digits in the prime factorization of the given number.
Example − 625, prime factors of number 625 is 54.
The number of digits in 625 is 3.
The number of digits in 54 is 2.
3 is strictly greater than 2. Hence, 625 is a frugal number.
First few frugal number are − 125, 128, 243, 256, 343, 512, 625, etc.
Let’s take an example to understand the problem
Input: n = 128 Output: Frugal number Explanation : Factors of 128 are 2^7, number of digits 2. The number of digits in 128 is 3. The number is a frugal number.
Solution Approach
One solution to the problem is by checking if the current number n is a frugal number. For this, we will find the prime factors of n and count the number of digits in the factorization and then count the number of digits in the number. If the number of digits in the number is greater than numbers in factors, the number is a frugal number otherwise it is not.
Example
Program to illustrate the working of our solution
#include <bits/stdc++.h> using namespace std; vector<long int> calcPrimeNum(long int n){ bool primeNos[n + 1]; memset(primeNos, true, sizeof(primeNos)); for (int i = 2; i * i <= n; i++) { if (primeNos[i] == true) { for (int j = i * 2; j <= n; j += i) primeNos[j] = false; } } vector<long int> allPrimeNumbers; for (int i = 2; i < n; i++) if (primeNos[i]) allPrimeNumbers.push_back(i); return allPrimeNumbers; } int countNumDigits(long int n){ long long int num = n; int digitCount = 0; while (num != 0) { num = num / 10; digitCount++; } return digitCount; } bool isFrugalNum(long int n){ vector<long int> primeNum = calcPrimeNum(n); long int num = n; long int factorDigitCount = 0; for (int i = 0; i < primeNum.size(); i++) { if (num % primeNum[i] == 0) { long int k = 0; while (num % primeNum[i] == 0) { num = num / primeNum[i]; k++; } if (k == 1) factorDigitCount = factorDigitCount + countNumDigits(primeNum[i]); else if (k != 1) factorDigitCount = factorDigitCount + countNumDigits(primeNum[i]) + countNumDigits(k); } } return (countNumDigits(n) > factorDigitCount && factorDigitCount != 0); } int main(){ long int n = 625; cout<<"The number "<<n<<" is ";isFrugalNum(n)? cout<<"a Frugal number\n" : cout << "not a Frugal number\n"; return 0; }
Output
The number 625 is a Frugal number