Fibonacci数列的和式表达及wat实现
August 29th, 2024

设数列的第nn项为f(n)f(n),则根据定义有f(n)=f(n1)+f(n2)f(n)=f(n-1)+f(n-2)。由此易得,

f(n)=f(1)+f(0)+f(1)++f(n2)f(n) = f(1) + f(0) + f(1) + … + f(n-2)

用wat语言(wasm)可实现求和法计算f(n)f(n)如下:

(module
    (func $fib (export "fib") (param $n i32) (result i32)
        (local $tmp i32)
        
        (local.set $tmp (i32.const 1))
        
        (block $break
            (br_if $break (i32.lt_s
                                (local.get $n)
                                (i32.const 2)))
            (loop $loop
                (local.set $tmp (i32.add
                                    (call $fib (i32.add
                                                    (local.get $n)
                                                    (i32.const -2)))
                                    (local.get $tmp)))
                (br_if $loop (i32.gt_s
                                (local.tee $n (i32.add (local.get $n) (i32.const -1)))
                                (i32.const 1)))
            )
        )

        local.get $tmp        

    )
)

直接用f(n)=f(n-1)+f(n-2)的逻辑,wat代码为:
(module
    (func $fib (export "fib") (param $n i32) (result i32)
        (local $tmp i32)
        
        (local.set $tmp (i32.const 1))
        
        (block $break
            (br_if $break (i32.lt_s
                                (local.get $n)
                                (i32.const 2)))
            (local.set $tmp (i32.add
                                    (call $fib (i32.add
                                                    (local.get $n)
                                                    (i32.const -2)))
                                    (call $fib (i32.add
                                                    (local.get $n)
                                                    (i32.const -1)))))
        )
        local.get $tmp        
    )
)
Subscribe to Aulee
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.
More from Aulee

Skeleton

Skeleton

Skeleton