Given two numbers n and r, the task is to find the value of nPr.
nPr represents n permutation r which is calculated as n!/(n-k)!. Permutation refers to the process of arranging all the members of a given set to form a sequence. The number of permutations on a set of n elements is given by n! where “!” represents factorial.
nPr = n! / (n - r)!
Program:
C++
#include<bits/stdc++.h>
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);
}
int main()
{
int n = 5;
int r = 2;
cout << n << "P" << r << " = " << nPr(n, r);
}
|
Java
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
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))
n = 5
r = 2
print (n, "P" , r, "=" , nPr(n, r))
|
C#
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));
}
}
|
PHP
<?php
function fact( $n )
{
if ( $n <= 1)
return 1;
return $n * fact( $n - 1);
}
function nPr( $n , $r )
{
return floor (fact( $n ) /
fact( $n - $r ));
}
$n = 5;
$r = 2;
echo $n , "P" , $r , " = " , nPr( $n , $r );
?>
|
Javascript
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));
}
let n = 5;
let r = 2;
document.write(n, "P" , r, " = " , nPr(n, r));
|
Time Complexity: O(N), where N is the given number.
Auxiliary Space: O(N), for recursive stack space while calculating factorial.
Optimization for multiple queries of nPr
If there are multiple queries for nPr, we may precompute factorial values and use the same for every call. This would avoid the computation of the same factorial values again and again.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!