本文概述
- C ++
- Java
- Python 3
- C#
- 的PHP
设n次谐波数为Hn.
【算法题(查找第N个谐波数的程序)】谐波序列如下:
H1 = 1例子:
H2 = H1 + 1/2
H3 = H2 + 1/3
H4 = H3 + 1/4
。 。 。
Hn = Hn-1 + 1/n
Input : N = 5
Output : 2.45Input : N = 9
Output : 2.71786
这个想法是从H1遍历, 然后连续从H1寻找H2, 从H2寻找H3 .....依此类推。
下面是查找第N个谐波数的程序:
C ++
//CPP program to find N-th Harmonic Number#include <
iostream>
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<
<
nthHarmonic(N);
return 0;
}
Java
//Java program to find N-th Harmonic Numberimport 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 Codepublic 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 /ireturn 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
<
?php
//PHP program to find
//N-th Harmonic Number//Function to find N-th
//Harmonic Number
function nthHarmonic( $N )
{
//H1 = 1
$harmonic = 1.00;
//loop to apply the forumula
//Hn = H1 + H2 + H3 ... +
//Hn-1 + Hn-1 + 1/n
for ( $i = 2;
$i <
= $N ;
$i ++)
{
$harmonic += (float)1 /$i ;
}return $harmonic ;
}//Driver Code
$N = 8;
echo nthHarmonic( $N );
//This code is contributed
//by Shivi_Aggarwal
?>
输出如下:
2.71786
时间复杂度: O(N)
推荐阅读
- 算法题(硬币游戏赢家,每个玩家都有三个选择)
- 瑞士信贷技术分析师面试
- PHP上传进度条实现详细示例
- 重新排列数组,使索引相同的子集的总和与原始数组中的总和不同
- 按照数组中出现元素的顺序对链表进行排序
- 硬实时和软实时系统之间有什么区别()
- 算法题(最大的按行和按列排序的子矩阵)
- u盘打开盘自制,教您如何迅速自制一个PE系统
- u盘装系统工具,教您u盘怎样安装win7系统