- Index
- » Usage and Applications
- » OpenModelica Usage and Applications
- » Factorial function
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)
- sjoelund.se
- 1700 Posts
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
- sjoelund.se
- 1700 Posts
- Index
- » Usage and Applications
- » OpenModelica Usage and Applications
- » Factorial function