There are several problems with your code.
The first one is that you are missing a couple of semicolons to suppress output and delineate substatements in a compound function.
The second problem is that you are trying to assign a new value to x
within the function definition. This doesn't work. x
already has the value of whatever number you give. You need to have a local variable inside the Module
that starts off having the value of the passed parameter, x
.
Fixing these two things gives
prime[x_] :=
Module[{a, i, y, xx = x}, a = x/2; i = 0 ;
If[IntegerQ[x] == False, Print["Input integer."]; Return[]];
While[IntegerQ[xx] == True, xx = xx/2; i = i + 1;]; y = xx/2^i;
Return[{i, y}]]
This gets rid of the error message (which it would have been helpful to have provided), and outputs an answer that is (I think) what you want.
I'd like to make some other suggestions to make your code simpler and more "Mathematica-like". Firstly, you can assign the initial values of your local variables a
and i
in the first argument of Module
. This simplifies the complexity of your code.
You could also remove the If
statement by using the pattern-matching functionality of Mathematica so that your function only operates for integer inputs. Finally, you don't actually need that final Return
. You would then have:
prime[x_Integer] :=
Module[{a = x/2, i = 0, y, xx = x},
While[IntegerQ[xx] == True, xx = xx/2; i = i + 1;];
y = xx/2^i; {i, y}]
This gives the same output, at least for the couple of values I tried.
You could then define a different version of the function for non-integer input, like this:
prime::notint = "`1` is not an integer. Please provide integer input";
prime[x_] := Message[prime::notint, x]
So if you write:
prime[4.1]
You get a helpful error message.
prime::notint: 4.1 is not an integer. Please provide integer input