Skip to content
This repository has been archived by the owner on Aug 9, 2024. It is now read-only.

Commit

Permalink
Usar Tailcall
Browse files Browse the repository at this point in the history
Implementar versión con tailcall para evitar stackoverflow en entradas relativamente grandes
  • Loading branch information
Laifsyn committed Jun 5, 2024
1 parent ecff4af commit a3ec0a5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/main/java/com/utp/clsEstructuraDatos/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,7 @@ path = "laboratorio_2_rust/main.rs"
colored = "2.1.0"
inquire = "0.7.5"
num-bigint = "0.4.5"
tailcall = "1.0.1"

[features]
tailcall = []
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ fn spawn_app() {
}
};
};

// Ejecutar la función seleccionada
#[rustfmt::skip]
match funcion {
Expand All @@ -76,7 +77,7 @@ fn spawn_app() {
println!("{}", format!("Factorial({}) no es calculable", args[0]).bright_red().bold());
continue;
};
println!("Factorial({}) = {factorial} ({} digitos)", args[0], factorial.to_string().len());
println!("Factorial({}) = {factorial} \n{}", args[0], format!("({} digitos)", factorial.to_string().len()).on_black().cyan());
},
};
match Confirm::new("Desea salir?").with_placeholder("Y/N").prompt() {
Expand Down Expand Up @@ -168,6 +169,7 @@ fn fib(nth: usize) -> Option<u128> {
}

/// Factorial Recursivo
#[cfg(not(feature = "tailcall"))]
fn factorial(n: usize) -> Option<num_bigint::BigInt> {
if let 0..=1 = n {
return Some(1.into());
Expand All @@ -176,6 +178,23 @@ fn factorial(n: usize) -> Option<num_bigint::BigInt> {
}
}

/// Factorial Recursivo
/// Compilar con `tailcall` para obtener esta función
/// `cargo run --release --features "tailcall"`
#[cfg(feature = "tailcall")]
fn factorial<T:TryInto<u16>>(n: T) -> Option<num_bigint::BigUint> {
use num_bigint::BigUint;
let n = n.try_into().ok()?;
#[tailcall::tailcall]
fn tail_recursive_factorial(n: u16, acc: BigUint) -> BigUint {
match n {
0 => acc,
_ => tail_recursive_factorial(n - 1, acc * n)
}
}
return Some(tail_recursive_factorial(n, 1u8.into()));
}

fn Q(a: usize, b: usize) -> usize {
if a < b {
return 0;
Expand Down

0 comments on commit a3ec0a5

Please sign in to comment.