四面体数

一个数被称为四面体数,如果它可以表示为一个三角形底和三个边的金字塔,则称为四面体数。n th 四面体数是前n个数的和 三角数 . 前十个四面体数是: 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, …

null

图片[1]-四面体数-yiteyi-C++库

n的公式 th 四面体数:

Tn = (n * (n + 1) * (n + 2)) / 6

证据:

The proof uses the fact that the nth tetrahedral number is given by,Trin = (n * (n + 1)) / 2It proceeds by induction.Base CaseT1 = 1 = 1 * 2 * 3 / 6Inductive StepTn+1 = Tn + Trin+1Tn+1 = [((n * (n + 1) * (n + 2)) / 6] + [((n + 1) * (n + 2)) / 2]Tn+1 = (n * (n + 1) * (n + 2)) / 6

以下是上述理念的实施:

C++

// CPP Program to find the
// nth tetrahedral number
#include <iostream>
using namespace std;
int tetrahedralNumber( int n)
{
return (n * (n + 1) * (n + 2)) / 6;
}
// Driver Code
int main()
{
int n = 5;
cout << tetrahedralNumber(n) << endl;
return 0;
}


JAVA

// Java Program to find the
// nth tetrahedral number
class GFG {
// Function to find Tetrahedral Number
static int tetrahedralNumber( int n)
{
return (n * (n + 1 ) * (n + 2 )) / 6 ;
}
// Driver Code
public static void main(String[] args)
{
int n = 5 ;
System.out.println(tetrahedralNumber(n));
}
}
// This code is contributed by Manish Kumar Rai.


python

# Python3 Program to find the
# nth tetrahedral number
def tetrahedralNumber(n):
return (n * (n + 1 ) * (n + 2 )) / 6
# Driver Code
n = 5
print (tetrahedralNumber(n))


C#

// C# Program to find the
// nth tetrahedral number
using System;
public class GFG{
// Function to find Tetrahedral Number
static int tetrahedralNumber( int n)
{
return (n * (n + 1) * (n + 2)) / 6;
}
// Driver code
static public void Main ()
{
int n = 5;
Console.WriteLine(tetrahedralNumber(n));
}
}
// This code is contributed by Ajit.


PHP

<?php
// PHP Program to find the
// nth tetrahedral number
function tetrahedralNumber( $n )
{
return ( $n * ( $n + 1) * ( $n + 2)) / 6;
}
// Driver Code
$n = 5;
echo tetrahedralNumber( $n );
// This code is contributed by mits
?>


Javascript

<script>
// JavaScript Program to find the
// nth tetrahedral number
// Function to find Tetrahedral Number
function tetrahedralNumber(n)
{
return (n * (n + 1) * (n + 2)) / 6;
}
// Driver code
let n = 5;
document.write(tetrahedralNumber(n));
// This code is contributed by code_hunt.
</script>


输出:

35

时间复杂性 :O(1)。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享