📜  第N个礼貌数字

📅  最后修改于: 2021-04-26 06:59:43             🧑  作者: Mango

礼貌数字是一个正整数,可以写为两个或多个连续的正整数之和。给定N,找到第N个礼貌数字。
例子:

Input : 4
Output : 7
Explanation: The first 3 are 3(1+2), 5(2+3), 
             6(1+2+3).

Input : 7
Output : 11
Explanation:  3, 5, 6, 7, 9, 10, 11.

存在一个有趣的模式,即礼让数字系列中不存在2的幂。基于这个事实,存在第N个礼貌数的以下公式(Lambek–Moser定理)。
f(n) = n+ \left \lfloor log_2 (n+ log_2 n) \right \rfloor
在这里要找到第N个礼貌数字,我们必须在上式中将n为n + 1
内置的日志函数计算log base-e,因此将其除以log base-e 2将得到log base-2的值。
下面给出的是上述方法的实现:

C++
// CPP program to find Nth polite number
#include 
using namespace std;
 
// function to evaluate Nth polite number
double polite(double n)
{
    n += 1;
    double base = 2;
    return n + (log((n + (log(n) /
                 log(base))))) / log(base);
}
 
// driver code
int main()
{
    double n = 7;
 
    cout << (int)polite(n);
    return 0;
}


Java
// Java program for finding N-th polite number
import java.io.*;
 
class GFG {
 
    // function to find N-th polite number
    static double polite(double n)
    {
        n += 1;
        double base = 2;
        return n + (Math.log((n + (Math.log(n) /
               Math.log(base))))) / Math.log(base);
    }
 
    // driver code
    public static void main(String[] args)
    {
        double n = 7;
        System.out.println((int)polite(n));
    }
}


Python
import math
# function to find Nth polite number
def Polite(n):
    n = n + 1
    return (int)(n+(math.log((n + math.log(n, 2)), 2)))
 
# Driver code
n = 7
print Polite(n)


C#
// Java program for finding
// N-th polite number
using System;
 
class GFG {
 
    // Function to find N-th polite number
    static double polite(double n)
    {
        n += 1;
        double base1 = 2;
        return n + (Math.Log((n + (Math.Log(n) /
                     Math.Log(base1))))) /
                     Math.Log(base1);
    }
 
    // Driver code
    public static void Main(String []args)
    {
        double n = 7;
        Console.Write((int)polite(n));
    }
}
 
// This code is contributed by
// Smitha Dinesh Semwal


PHP


Javascript


输出:

11

参考:维基百科