HW 3, problem 1.22

By Nasser Abbasi, PHY 240, feb 2, 2002.

 

 

Part (A)

Source code

 

function [realPart,powerToTen] =nma_doubleFactorial(n)

% FUNCTION [realPart,powerToTen]=nma_doubleFactorial(n)

%

% compute double factorial of a number using the equation

% n!! = n  (n-2)  (n-4) .... 6 x 4 x 2   for even n

%                            5 x 3 x 1   for odd  n

%

% INPUT

%   n:  The number to find double factorial for.

% OUTPUT

%   output is returned in the form of   [realPart,powerOfTen]

%   where n!! = realPart x 10^(powerToTen)

%  

% realPart : the value in the above expression.

% powerToTen : the power to raise 10 to as shown in the above expression.

%

% This program also prints the final n!! number for

% display purposes.

 

% by Nasser Abbasi

% HW 3, 1.22. PHY 240, Feb 2, 2002

 

if nargin ~=1

    error('missing input argument');

end

 

if n <= 0

    error('positive value is expected');

end

 

v=0;

savedN= n;

 

while 1

    v= v + log10(n);

    n=n-2;

    if n <= 0

        powerToTen = floor(v);

        realPart = v - powerToTen;

       

        % since log10(n!!) = A + B

        % so, n!! = 10 ^(A+B) = 10^A * 10^B 

        % where A is the powerToTen, and 10^B will be the realPart.

       

        realPart = 10^realPart;

       

        disp(sprintf('%d!! = %f x 10^%d',savedN,realPart,powerToTen));

       

        return;

    end

end

 

 

 

OUTPUT

 

» help nma_doubleFactorial

 

  FUNCTION [realPart,powerToTen]=nma_doubleFactorial(n)

 

  compute double factorial of a number using the equation

  n!! = n  (n-2)  (n-4) .... 6 x 4 x 2   for even n

                             5 x 3 x 1   for odd  n

 

  INPUT

    n:  The number to find double factorial for.

  OUTPUT

    output is returned in the form of   [realPart,powerOfTen]

    where n!! = realPart x 10^(powerToTen)

   

  realPart : the value in the above expression.

  powerToTen : the power to raise 10 to as shown in the above expression.

 

  This program also prints the final n!! number for

  display purposes.

 

 

Example 1

 

» [A,B]=nma_doubleFactorial(1000)

1000!! = 3.993984 x 10^1284

 

A =

 

    3.9940

 

 

B =

 

        1284

 

 

Example 2

 

»

»

» clear all

» [A,B]=nma_doubleFactorial(2001)

2001!! = 1.539068 x 10^2870

 

A =

 

    1.5391

 

 

B =

 

        2870

 

Example 3

 

»

»

»

» clear all

» [A,B]=nma_doubleFactorial(10000)

10000!! = 5.972727 x 10^17830

 

A =

 

    5.9727

 

 

B =

 

       17830

 

 

Example 4

 

»

»

»

» clear all

» [A,B]=nma_doubleFactorial(314159)

314159!! = 4.313460 x 10^795273

 

A =

 

    4.3135

 

 

B =

 

      795273

 

»