How to write a semifactorial function that iterates up to the input?
5 views (last 30 days)
I'm currently trying to write a function that calculates the semifactorial of an input statement whether it's odd or even, but I can't figure out how to make it iterate to the input statement.
The semifactorial of n is the product of the integers between 1 and n which have the same parity (even or odd) as n. For example, 7‼ = 1 × 3 × 5 × 7 = 105, and 8‼ = 2 × 4 × 6 × 8 = 384.
Here's my code so far:
function [ factorial ] = FactorialPi( num )
i = 0;
factorial = ;
for i = 0:2:num
if mod(num, 2) ~= 0
num = (2 * i) + 1;
%else mod(num, 2) == 0
% i = (2 * i);
factorial = [factorial;num]
My output when I call FactorialPi(7) is:
Any help would be greatly appreciated, thank you!
The semifactorial of
Cedric Wannaz on 7 Oct 2017
Edited: Cedric Wannaz on 7 Oct 2017
This is a good start as you are trying, as a first step, to operate a bit how you would proceed by hand, element by element in a loop.
The next step is to realize that MATLAB can operate on arrays:
>> x = 1 : 3 : 11
1 4 7 10
defines a row vector, it is actually how you define the pool of values that your loop variable must take through iterations. Now say you have a vector of values, would you be able to compute their product without using a loop? You probably saw the function SUM, maybe there is an equivalent for products? [-> Google or Doc]
Here is an element-wise square and a sum to illustrate usual operations with arrays:
>> x.^2 % Element-wise square.
1 16 49 100
>> sum( x ) % Sum of all elements.
Once you understand this you'll know two things: how to build vectors of linearly spaced elements from a lower bound to an upper bound, and how to compute their product.
You will be in a situation where you know how to define the upper bound as it is the input of the function, but you will have to find a way to define the lower bound, which is a number that is either 1 or 2 depending the parity of the input. Maybe there is a way .. maybe you almost found it already (!)