C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Program to print the combination (nCr) of the given numberCombination (nCr) can be defined as the combination of n things taken r at a time without any repetition. ncr can be calculated as, nCr = [n(n-1) ... (n-r+1)] / r(r-1)...1 AlgorithmMAIN
nCr(n r)
fact(n)
Java Programimport java.util.*; class Combination { static int nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } static int fact(int n) { int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } public static void main(String[] args) { int n,r; System.out.println("Enter the value of n and r?"); Scanner sc = new Scanner(System.in); n = sc.nextInt(); r = sc.nextInt(); System.out.println("nCr = "+nCr(n, r)); } } Output: Enter the value of n and r? 6 4 nCr = 15 C Program#include <stdio.h> int fact(int z); void main() { int n, r, nCr; printf("Enter the value of n and r?"); scanf("%d %d",&n,&r); nCr = fact(n) / (fact(r) * fact(n - r)); printf("\nnCr = %d", nCr); } int fact(int z) { int f = 1, i; if (z == 0) { return(f); } else { for (i = 1; i <= z; i++) { f = f * i; } } return(f); } Output: Enter the value of n and r? 5 3 nCr = 10 Python Programdef fact(z): f = 1 if z == 0: return f; else: for i in range(1,z+1): f = f * i; return f; n=int(input("Enter the value of n")) r = int(input("Enter the value of r")) nCr = fact(n) / (fact(r) * fact(n - r)); print("\nnCr = %d" %(nCr)); Output: Enter the value of n 5 Enter the value of r 3 nCr = 10 C# Programusing System; class Combination { static int nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } static int fact(int n) { int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } public static void Main() { int n,r; Console.WriteLine("Enter the value of n and r?"); n = Convert.ToInt32(Console.ReadLine()); r = Convert.ToInt32(Console.ReadLine()); Console.Write("nCr = "+nCr(n, r)); } } Output: Enter the value of n and r? 5 3 nCr = 10 PHP Program<?php function nCr( $n, $r) { return fact($n) / (fact($r) * fact($n - $r)); } function fact( $n) { $res = 1; for ( $i = 2; $i <= $n; $i++) $res = $res * $i; return $res; } echo "Enter the value of n and r?"; $n = readline(); $r = readline(); echo "ncr = "; echo nCr($n, $r); ?> Output: Enter the value of n and r? 5 3 nCr = 10
Next Topic#
|