给定两个数字n和r,任务是找到nPr的值。
nPr代表n个置换r,其计算公式为n!/(nk)!。 。排列是指将给定集合的所有成员排列成一个序列的过程。一组n个元素上的排列数由n!在哪里 ”!”代表阶乘。
nPr = n! / (n - r)!
程序:
C++
// CPP program to calculate nPr
#include
using namespace std;
int fact(int n)
{
if (n <= 1)
return 1;
return n * fact(n - 1);
}
int nPr(int n, int r)
{
return fact(n) / fact(n - r);
}
// Driver code
int main()
{
int n = 5;
int r = 2;
cout << n << "P" << r << " = " << nPr(n, r);
}
// This code is contributed by
// Surendra_Gangwar
Java
// Java program to calculate nPr
import java.util.*;
public class GFG {
static int fact(int n)
{
if (n <= 1)
return 1;
return n * fact(n - 1);
}
static int nPr(int n, int r)
{
return fact(n) / fact(n - r);
}
public static void main(String args[])
{
int n = 5;
int r = 2;
System.out.println(n + "P" + r + " = "
+ nPr(n, r));
}
}
Python3
# Python3 program to calculate nPr
import math
def fact(n):
if (n <= 1):
return 1
return n * fact(n - 1)
def nPr(n, r):
return math.floor(fact(n) /
fact(n - r))
# Driver code
n = 5
r = 2
print(n, "P", r, "=", nPr(n, r))
# This code contributed by Rajput-Ji
C#
// C# program to calculate nPr
using System;
class GFG
{
static int fact(int n)
{
if (n <= 1)
return 1;
return n * fact(n - 1);
}
static int nPr(int n, int r)
{
return fact(n) / fact(n - r);
}
public static void Main()
{
int n = 5;
int r = 2;
Console.WriteLine(n + "P" + r + " = "
+ nPr(n, r));
}
}
/* This code contributed by PrinciRaj1992 */
PHP
Javascript
// Javascript program to calculate nPr
function fact(n)
{
if (n <= 1)
return 1;
return n * fact(n - 1);
}
function nPr(n, r)
{
return Math.floor(fact(n) /
fact(n - r));
}
// Driver code
let n = 5;
let r = 2;
document.write(n, "P", r, " = ", nPr(n, r));
// This code is contributed by gfgking
输出:
5P2 = 20
优化多个nPr查询
如果对nPr有多个查询,我们可以预先计算阶乘值,并在每次调用时使用相同的值。这将避免一次又一次地计算相同的阶乘值。