-
Notifications
You must be signed in to change notification settings - Fork 690
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1000 from Horiol/master
#755 Catalan numbers in Rust
- Loading branch information
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
use std::io; | ||
|
||
fn main() { | ||
println!("Enter number value: "); | ||
let mut input = String::new(); | ||
io::stdin().read_line(&mut input).ok().expect("failed to read line"); | ||
let val: u64 = input.trim().parse().expect("Please type a number"); | ||
println!("Catalan number is: {}", catalan(val)); | ||
} | ||
|
||
fn catalan(n: u64) -> u64 { | ||
if n == 0 || n == 1 { | ||
return 1; | ||
} | ||
|
||
let mut catalan_list = Vec::new(); | ||
catalan_list.push(1); | ||
catalan_list.push(1); | ||
|
||
for index in 2..(n+1) { | ||
catalan_list.push(0); | ||
for other_index in 0..index { | ||
catalan_list[index as usize] = catalan_list[index as usize] | ||
+ catalan_list[other_index as usize] * catalan_list[(index - other_index - 1) as usize]; | ||
} | ||
} | ||
return catalan_list[n as usize]; | ||
} |