- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 polite number in C++
A polite number is a positive number that can be written as the sum of 2 or more consecutive positive numbers.
The series of polite numbers are
3 5 6 7 9 10 11 12 13 14...
There exists a formula to find the n-th polite number. The formula is n + log2(n + log2(n)). The default log computes with base e. We need to compute using base 2. Divide the default log result with log(2) to get the value of log with base e.
Algorithm
- Algorithm to the n-th polite number is straightforward.
- Initialise the number N.
- Use the above formula to compute the n-th polite number.
- Make sure to increment the value of n by 1 before computing the n-th polite number.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; double getNthPoliteNumber(double n) { n += 1; return n + (log((n + (log(n) / log(2.0))))) / log(2.0); } int main() { double n = 10; cout << (int)getNthPoliteNumber(n) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
14
Advertisements