In[58]:=
Clear[ realcuberoot]
realcuberoot[x_]:= If[ x>= 0,
x^(1/3), (* True value *)
-(-x)^(1/3) (*False value *)
]
In[59]:=
realcuberoot[-1]
Out[59]=
-1
The function returns the real cube root of a negative number. Observe that
we
placed a comment about the result in the If statement. Mathematica
comments
are placed between the expressions (* and *).
Another example of an If statement is the following in which we check if a
number
is a perfect square.
In[60]:=
squareQ[ n_]:= If[ Floor[ N[Sqrt[n]]]^2== n,
True, (* Yes, aperfect square *)
False (* not a square *)
]
In[61]:=
squareQ[196]
Out[61]=
True
In[62]:=
squareQ[255]
Out[62]=
False
The function can be written without any If statements by writing
squareQ[n_]:= Floor[ N[ Sqrt[n]]]^2 == n;
This is because the result of the test for equality is a True or False. The
following are
the relational operators that can be used. These can be combined with logical
operators,
And, Or , or Not to create all the tests that we need.
x = = y Is x equal to y?
x!= y Is x not equal to y?
x> y Is x greater than y?
x< y Is x less than y.
Similarly, the relations >= and <= are self-explanatory. The only issue
to keep in mind is
that two equal signs are necessary for a test of equality. A single = is an
assignment of
one to the other and not a test. The boolean AND operator is represented
by
&& and the logical OR by ||. The complement is represented by the
exclamation !.
For example, to test if n is a prime that is not of the form 5k+3, we can
use
PrimeQ[n] && !( Mod[ n,5]==3).
Exercise: Write a function that returns True if a number is either a prime or a
perfect square,
and False otherwise..
Write another function that returns True if a number is a prime or the square
of a
prime, and False otherwise.
Up to Loops and Conditionals