-
-
Save RandyMcMillan/d694d2d6dcb0660b77bf3afbdce135da to your computer and use it in GitHub Desktop.
pascals_triangle.rs
This file contains hidden or 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
fn print_pascals_triangle_in_binary(num_rows: usize) { | |
if num_rows == 0 { | |
return; | |
} | |
let mut current_row: Vec<u64> = vec![1]; // Using u64 for larger numbers | |
println!("{:b}", current_row[0]); // Print 1 in binary | |
for r in 1..num_rows { | |
let mut next_row: Vec<u64> = vec![1]; // First element is 1 | |
for c in 1..r { | |
// Each element is the sum of the two numbers directly above it | |
let sum = current_row[c - 1] + current_row[c]; | |
next_row.push(sum); | |
} | |
next_row.push(1); // Last element is 1 | |
// Print the row in binary | |
for (i, &val) in next_row.iter().enumerate() { | |
print!("{:b}", val); // {:b} formats an integer as binary | |
if i < next_row.len() - 1 { | |
print!(" "); // Add space between binary numbers | |
} | |
} | |
println!(); | |
current_row = next_row; | |
} | |
} | |
fn main() { | |
println!("Pascal's Triangle in Binary (5 rows):"); | |
print_pascals_triangle_in_binary(5); | |
println!("\nPascal's Triangle in Binary (10 rows):"); | |
print_pascals_triangle_in_binary(10); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment