Problem and Solution!
I found an interesting problem on net and as a noivce decided to solve it all by self with the help of PHP.
Problem:”If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
”
Solution:
“<?php
for($counter=1; $counter < 1000 ; $counter ++)
{
//echo ”
“;
//echo ”
“.$counter.”–> “;
$int_var1 = ($counter/3); //current counter will be divided by 3
$int_var2 = ($counter/5); //current counter will be divided by 5
$str_type1 = gettype($int_var1); //This will return integer if counter was divided by 3 properly
$str_type2 = gettype($int_var2); //This will return integer if counter was divided by 5 properly
if ($str_type1 == ‘integer’ || $str_type2 == ‘integer’ ) //to check which “counter” was properly divided
{
//echo “This is integer”;
$int_result = $int_result+$counter;
}
else
{
//echo ” NON INTEGER” ;
}
}
echo “Result is: $int_result “;
?>
“
November 19, 2009 - 2:19 am
Dear Asim,
You can use modulus operator (%) also for this purpose. Change your line:
$int_var1 = ($counter/3); //current counter will be divided by 3
$int_var2 = ($counter/5); //current counter will be divided by 5
with
$int_var1 = ($counter % 3); //current counter will be divided by 3
$int_var2 = ($counter % 5); //current counter will be divided by 5
and rather checking for gettype(), you can check for the remainder, which will be returned in your variables $int_var1 and $int_var2. If remainder is 0 (zero) then it’s your required number otherwise remainder will be greater than 0.
Modulus is an arithmetic operator and much faster than type casting like you are doing with gettype() and checking on the string “integer”.
FYI: Type casting means converting data from one data type to another. i.e: converting a digit into string or into boolean, this is called type casting, and it always has payload.
November 19, 2009 - 2:23 am
For a reference on Arithmetic Operators, see PHP official manual entry at :
http://www.php.net/manual/en/language.operators.arithmetic.php
December 25, 2009 - 10:44 am
gud one