📜  查找第N个谐波数的程序

📅  最后修改于: 2021-05-04 19:39:32             🧑  作者: Mango

给定数字N。任务是找到第N个谐波数。
设n次谐波数为H n
谐波序列如下:

例子

Input : N = 5
Output : 2.45

Input : N = 9
Output : 2.71786

想法是从H1遍历,然后连续从H1寻找H2,从H2寻找H3 …..依此类推。
下面是查找第N个谐波数的程序:

C++
// CPP program to find N-th Harmonic Number
 
#include 
using namespace std;
 
// Function to find N-th Harmonic Number
double nthHarmonic(int N)
{
    // H1 = 1
    float harmonic = 1.00;
 
    // loop to apply the forumula
    // Hn = H1 + H2 + H3 ... + Hn-1 + Hn-1 + 1/n
    for (int i = 2; i <= N; i++) {
        harmonic += (float)1 / i;
    }
 
    return harmonic;
}
 
// Driver Code
int main()
{
    int N = 8;
     
    cout<


Java
// Java program to find N-th Harmonic Number
 
import java.io.*;
 
class GFG {
     
// Function to find N-th Harmonic Number
static double nthHarmonic(int N)
{
    // H1 = 1
    float harmonic = 1;
 
    // loop to apply the forumula
    // Hn = H1 + H2 + H3 ... + Hn-1 + Hn-1 + 1/n
    for (int i = 2; i <= N; i++) {
        harmonic += (float)1 / i;
    }
 
    return harmonic;
}
 
// Driver Code
 
    public static void main (String[] args) {
            int N = 8;
     
    System.out.print(nthHarmonic(N));
     
    }
}
// This code is contributed
// by ajit


Python 3
# Python3 program to find
# N-th Harmonic Number
 
# Function to find N-th Harmonic Number
def nthHarmonic(N) :
 
    # H1 = 1
    harmonic = 1.00
 
    # loop to apply the forumula
    # Hn = H1 + H2 + H3 ... +
    # Hn-1 + Hn-1 + 1/n
    for i in range(2, N + 1) :
        harmonic += 1 / i
 
    return harmonic
     
# Driver code    
if __name__ == "__main__" :
 
    N = 8
    print(round(nthHarmonic(N),5))
 
# This code is contributed by ANKITRAI1


C#
// C# program to find N-th Harmonic Number
using System;
 
class GFG
{
     
// Function to find N-th Harmonic Number
static double nthHarmonic(int N)
{
    // H1 = 1
    float harmonic = 1;
 
    // loop to apply the forumula
    // Hn = H1 + H2 + H3 ... +
    // Hn-1 + Hn-1 + 1/n
    for (int i = 2; i <= N; i++)
    {
        harmonic += (float)1 / i;
    }
 
    return harmonic;
}
 
// Driver Code
static public void Main ()
{
    int N = 8;
     
    Console.Write(nthHarmonic(N));
}
}
 
// This code is contributed
// by Raj


PHP


Javascript


输出:
2.71786

时间复杂度:O(N)