ADVERTISEMENT
ADVERTISEMENT

PHP program to calculate factors of a given number

In this article, we are going to learn how to create a function in PHP that will help us calculate factors of any given number?
Submitted by Kongnyu Carine, on January 10, 2021

For instance, if we have to list the factors of a number y. Then, we have to look for all possible numbers within the range 0 to the number y (with 0 exclusive because we do not divide a number by 0) that gives no remainder when it divides y.

Example:

Input 6
Output {1,2,3,4,5,6,}.

Let's Write out a PHP function to do this for us:

Program/Source Code:

<?php
//We Define a function that gets
//an argument and return the factors
//of the number it got.
// Function definition
function factors_of_a_number($n)
{
    if ($n == 0)
    {
        // because we cannot divide 0/0 does not exist
        echo "Zero has no factors";
    }
    else
    {
        // format our answer to look good.
        print_r("The factors of $n are {");
        //We will use a for loop to loop through
        // each number in the series  1 to our number $n
        // dividing $n by each number
        for ($x = 1;$x <= $n;$x++)
        {
            // the modulus operator
            // helps us get the remainder of each division
            $factor = $n % $x;

            //we will check to see which number return a 0 as reminder
            // the we echo that number because it is a factor of our number $n.
            if ($factor == 0)
            {
                print_r($x . ",");
            }
        }
        print_r("}");
    }
}
print_r(factors_of_a_number(0) . "\n");
print_r(factors_of_a_number(50) . "\n");
?>

Output:

Zero has no factors
The factors of 50 are {1,2,5,10,25,50,}

PHP Basic Programs »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.