Home »
Rust »
Rust Programs
Rust program to calculate the value of nCr
Given the value or n, r, and we have to calculate the value of nCr using the Rust program.
Submitted by Nidhi, on October 01, 2021
Problem Solution:
Here, we will read the value of n and r from the user. Then we will calculate the nCr and print the result.
nCr:
nCr known as the combination is the method of selection of 'r' objects from a set of 'n' objects where the order of selection does not matter.
To find the value of nCr, we use the formula: nCr = n!/[r!( n-r)!]
Program/Source Code:
The source code to calculate the value of nCr is given below. The given program is compiled and executed successfully.
// Rust program to calculate the value of nCr
use std::io;
fn getFactorial(num:i32)->i32
{
let mut f:i32 = 1;
let mut i:i32 = 1;
if (num == 0)
{
return 1;
}
while(i <= num)
{
f = f * i;
i=i+1;
}
return f;
}
fn main()
{
let mut n:i32 =0;
let mut r:i32 =0;
let mut nCr:i32 =0;
let mut input1 = String::new();
let mut input2 = String::new();
println!("Enter value of n: ");
io::stdin().read_line(&mut input1).expect("Not a valid string");
n = input1.trim().parse().expect("Not a valid number");
println!("Enter value of r: ");
io::stdin().read_line(&mut input2).expect("Not a valid string");
r = input2.trim().parse().expect("Not a valid number");
nCr = getFactorial(n) / (getFactorial(r) * getFactorial(n - r));
println!("The nCr is: {}", nCr);
}
Output:
Enter value of n:
5
Enter value of r:
3
The nCr is: 10
Explanation:
Here, we read the value of n, r from the user. After that, we calculated the nCr and print the result.
Rust Basic Programs »