Code Generator | Power BI

Fibonacci Generator

This function generates a list of Fibonacci numbers using recursion.


Empty image or helper icon

Prompt

Write a function in Power BI that CRIE UMA LISTA DE FIBONACCI COM FUNÇÃO RECUSIVA

Answer

Function: Fibonacci

This function generates a list of Fibonacci numbers using recursion.

Parameters

  • n (required): An integer specifying the number of Fibonacci numbers to generate.

Return Type

  • list of integers: A list containing the Fibonacci numbers.

Exceptions

  • ValueError: Raised if the input parameter n is not a positive integer.

Code

let
    Fibonacci = (n as number) as list =>
        let
            result =
                if n = 1 then
                    {0}
                else if n = 2 then
                    {0, 1}
                else if n > 2 then
                    let
                        previous = Fibonacci(n-1),
                        second_previous = Fibonacci(n-2),
                        last_number = List.Last(previous) + List.Last(second_previous),
                        updated_result = previous & {last_number}
                    in
                        updated_result
                else
                    error "Input parameter 'n' must be a positive integer."
        in
            result
in
    Fibonacci

Usage Example

  1. Call the Fibonacci function with the desired number of Fibonacci numbers to generate.
  2. The function will return a list containing the Fibonacci numbers.

Code

let
    result = Fibonacci(10)
in
    result

Output

{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}

In this example, the Fibonacci function is called with the parameter 10. The function generates a list containing the first 10 Fibonacci numbers and returns it as the output. The resulting list is {0, 1, 1, 2, 3, 5, 8, 13, 21, 34}.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This function, called Fibonacci Generator, generates a list of Fibonacci numbers using recursion. It takes an input parameter, n, which specifies the number of Fibonacci numbers to generate. The function returns a list of integers, where each integer is a Fibonacci number. The Fibonacci numbers are generated recursively, with the base case being n = 1, where the function returns {0}. For n = 2, the function returns {0, 1}. For n > 2, the function calculates the previous Fibonacci numbers by calling itself recursively, adds the last numbers of the previous Fibonacci numbers, and returns the updated result. If the input parameter n is not a positive integer, a ValueError exception is raised.