PHP codes to find num and denom of fractions

### Author Topic: PHP codes to find num and denom of fractions  (Read 1952 times)

#### msu_math ##### PHP codes to find num and denom of fractions
« on: November 13, 2012, 10:52:09 AM »
Unlike integers and floats, addition and subtraction of several fractions (rational number) require finding least common multiple (LCM) of the denominators of those fractions. Also, simplifying a fractions requires finding greatest common divisor (GCD) of both numerator and denominator of that fractions.

Here, we quote the PHP codes to determine the numerator and denominator of a fraction. Note that both of the following functions recall the function FracCheck() which is included in the previously posted related articles.

function FracNumer(\$A)

{
if(FracCheck(\$A)==0) { return NULL; }
else
{
\$i=0;
\$len=strlen(\$A)-1;
while(\$A[\$i]!="/" && \$i<=\$len)
{
\$Numer=\$Numer.\$A[\$i];
\$i++;
}
return \$Numer;
}
}

function FracDenom(\$A)

{
if(FracCheck(\$A)==0) { return NULL; }
else
{
\$i=0; \$len=strlen(\$A)-1;
while(\$A[\$i]!="/" && \$i<=\$len)
{
\$i++;
}
if(\$i>\$len) {  return 1; }
else
{
\$i++;
while(\$i<=\$len)
{
\$Denom=\$Denom.\$A[\$i];
\$i++;
}
return \$Denom;
}
}
}
« Last Edit: November 15, 2012, 09:54:51 AM by msu_math »

Lecturer in Mathematics
Department of Natural Sciences
FSIT, DIU

#### msu_math ##### Re: PHP codes to find num and denom of fractions
« Reply #1 on: November 16, 2012, 06:52:45 PM »
Sample Return Values:

FracNumer("-11/7");    Return value:  "-11"

FracNumer("28");    Return value:  "28"

FracDenom("28");    Return value:  "1"

FracDenom("5/7");    Return value:  "7"

FracNumer("-3/5/7");    Return value:  NULL

*Because "-3/5/7" is not a valid fraction. ("-3/5/7" contains more than one "/")

FracDenom("51/7k");    Return value:  NULL

*Because "51/7k" is not a valid fraction. ("51/7k" contains non-digit character "k")

« Last Edit: November 16, 2012, 06:56:39 PM by msu_math »