0
$\begingroup$

Below I have my code that I created for finding the factorial of a number. The output I am getting when I enter MyFact[5] is Null Return[120]. I am rather new to Mathematica so I feel its a small semantic problem, but any help would be appreciated!

MyFact[n_] :=
  Module [
        {
         OneAgoFact,
         MyNewFact,
         Counter
        },
  MyNewFact = 1;
  OneAgoFact = 1;
  If[ n > 0,
    Counter = 1;
    While[Counter <= n,
        MyNewFact = OneAgoFact*Counter; 
        OneAgoFact = MyNewFact;
        Counter = Counter + 1;
        ]
        ]
   Return[MyNewFact]
  ]
$\endgroup$
  • 2
    $\begingroup$ You forgot to put a semicolon at the end of your If[]. If you do that, you can remove the Return[]. $\endgroup$ – J. M. will be back soon Sep 6 '17 at 2:13
1
$\begingroup$

Turning J.M.'s comment into an answer, you need to follow the If[...] statement with a semicolon. Otherwise If evaluates to what While evaluates to, which is Null, and without the semicolon Mathematica interprets If[...] Return[...] as multiplication.

ClearAll[MyFact]
MyFact[n_] := Module[{OneAgoFact, MyNewFact, Counter}, MyNewFact = 1;
  OneAgoFact = 1;
  If[n > 0, Counter = 1;
   While[Counter <= n, MyNewFact = OneAgoFact*Counter;
    OneAgoFact = MyNewFact;
    Counter = Counter + 1;]];
   MyNewFact]

Notice that you can replace Return[MyNewFact] simply with MyNewFact, as Module returns the evaluated form of its second argument.

One last note: you might want to avoid capital letters at the start of variable names, as they often conflict with built-in symbols. Symbols (i.e., variables or functions) which start with lowercase letters will never conflict with built-ins. Of course this is up to you.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.