How to resolve the algorithm Factorial step by step in the V (Vlang) programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Factorial step by step in the V (Vlang) programming language
Table of Contents
Problem Statement
Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative n errors is optional.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Factorial step by step in the V (Vlang) programming language
Source code in the v programming language
const max_size = 10
fn factorial_i() {
mut facs := [0].repeat(max_size + 1)
facs[0] = 1
println('The 0-th Factorial number is: 1')
for i := 1; i <= max_size; i++ {
facs[i] = i * facs[i - 1]
num := facs[i]
println('The $i-th Factorial number is: $num')
}
}
fn main() {
factorial_i()
}
const max_size = 10
fn factorial_r(n int) int {
if n == 0 {
return 1
}
return n * factorial_r(n - 1)
}
fn main() {
for i := 0; i <= max_size; i++ {
println('factorial($i) is: ${factorial_r(i)}')
}
}
const max_size = 10
fn factorial_tail(n int) int {
sum := 1
return factorial_r(n, sum)
}
fn factorial_r(n int, sum int) int {
if n == 0 {
return sum
}
return factorial_r(n - 1, n * sum )
}
fn main() {
for i := 0; i <= max_size; i++ {
println('factorial($i) is: ${factorial_tail(i)}')
}
}
const max_size = 10
struct Cache {
mut:
values []int
}
fn fac_cached(n int, mut cache Cache) int {
is_in_cache := cache.values.len > n
if is_in_cache {
return cache.values[n]
}
fac_n := if n == 0 { 1 } else { n * fac_cached(n - 1, mut cache) }
cache.values << fac_n
return fac_n
}
fn main() {
mut cache := Cache{}
for n := 0; n <= max_size; n++ {
fac_n := fac_cached(n, mut cache)
println('The $n-th Factorial is: $fac_n')
}
}
You may also check:How to resolve the algorithm Command-line arguments step by step in the Free Pascal programming language
You may also check:How to resolve the algorithm Greatest common divisor step by step in the C# programming language
You may also check:How to resolve the algorithm SEDOLs step by step in the VBScript programming language
You may also check:How to resolve the algorithm A+B step by step in the Little Man Computer programming language
You may also check:How to resolve the algorithm Combinations step by step in the Erlang programming language