N-th polite number in C++

C++Server Side ProgrammingProgramming

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

A polite number is a positive number that can be written as the sum of 2 or more consecutive positive numbers.

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.

Example

Let's see the code.

 Live Demo

#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

Conclusion

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

raja
Published on 29-Jun-2021 09:12:36
Advertisements