C# Program to Find nPr
Posted by Superadmin on August 15 2022 07:34:01

C# Program to Find nPr

 

 

This is a C# Program to calculate nPr.

Problem Description

This C# Program Calculates nPr.

Problem Solution

Here there are n! (n factorial) permutations of n symbols. An r-permutation of n symbols is a permutation of r of them. There are n!/(n – r)! different r-permutations of n symbols.

Program/Source Code

Here is source code of the C# Program to Calculate nPr. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Calculate nPr
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication40
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, r, per, fact, fact1;
            Console.WriteLine("Enter the Value of 'n' and 'r' " + 
                              "to find the Permutation :");
            n = Convert.ToInt32(Console.ReadLine());
            r = Convert.ToInt32(Console.ReadLine());
            fact = n;
            for (int i = n - 1; i >= 1; i--)
            {
                fact = fact * i;
            }
            int number;
            number = n - r;
            fact1 = number;
            for (int i = number - 1; i >= 1; i--)
            {
                fact1 = fact1 * i;
            }
            per = fact / fact1;
            Console.WriteLine("Permutation : {0}",per);
            Console.ReadLine();
        }
    }
}
Program Explanation

In this C# program, we are reading the two integer values using ‘n’ and ‘r’ variables respectively. Here we need to find all the possible permutation value. A permutation is a re-arrangement of elements of a set. Any duplication of the collected elements in different orders is allowed. A permutation therefore tends to be a large number.

 

The fact() function is used to find all possible rearrangement of the elements. If condition statement is used to check the value of ‘integer’ variable is less than or equal to 1. If the condition is true then return the value as 1.

Otherwise, if the condition is false, compute the value of integer with the next previous value i.e if the integer value is 3. Multiply the resulted value by 3*2 then the resultant value 6 with 1. Compute the difference between the values of ‘integer’ variable by the ‘r’ power variable value.

Runtime Test Cases
 
Enter the value of 'n' and 'r' to find the Permutation :
10
5
Permutation : 30240