Archived OpenModelica forums. Posting is disabled.

Alternative forums include GitHub discussions or StackOverflow (make sure to read the Stack Overflow rules; you need to have well-formed questions)


Forgot password? | Forgot username? | Register

Factorial function

Factorial function

Hello,

I'm a new Modelica user and I'm writing a code for factorial function in OMShell. However I came to a problem, which I don't know how to solve, since the next error keeps coming no matter what I do:

Error: No viable alternative near token: =

Here is the code I wrote:

function factorial
    input Integer n;
    output Integer y;
algorithm
    for i in 1:n loop
        if (n=0) then
        y := 0;
        else
        y := i*factorial(i-1);
        end if;
    end for;
end factorial;

I tried to erase and add semicolon in different places, but still did not work. Can somebody help me with this problem?

Re: Factorial function

Correct syntax is: if (n==0)

Re: Factorial function

Thank you for the answer. The function is now loaded successfully, but now the problem is that  whichever number I enter, function gives me number 0 as a result...Should I use any other statement to avoid the 0 result?

Re: Factorial function

Well, your functions starts the loop with n=1, so the n=0 case is undefined. You don't initialize y, so it gets random data (possibly 0). You then recursively call the function to multiply i by fac(i-1), which again ends with the undefined y (possibly 0).

You are mixing iterative and recursive styles. Choose one:

For a recursive factorial: https://github.com/OpenModelica/OpenMod … ctorial.mo

Or iterative: https://github.com/OpenModelica/OpenMod … on.mo#L235

Re: Factorial function

Thank you! Works properly! current/smile

There are 0 guests and 0 other users also viewing this topic