How to use Mathematical Formula In PHP

In this section, we use mathematical formula to calculate the LCM of two numbers. The LCM of two numbers is equal to the product of the two numbers divided by their Greatest Common Divisor (GCD).

Example:

PHP




<?php
  
function findGCD($a, $b) {
    while ($b != 0) {
        $temp = $b;
        $b = $a % $b;
        $a = $temp;
    }
    return $a;
}
  
function findLCM($a, $b) {
      
    $gcd = findGCD($a, $b);
  
    $lcm = ($a * $b) / $gcd;
  
    return $lcm;
}
  
$num1 = 12;
$num2 = 18;
  
echo "LCM : " . findLCM($num1, $num2);
  
?>


Output

LCM : 36

PHP Program to Find LCM of Two Numbers

Given two numbers, the task is to find the LCM of two numbers using PHP.

Examples:

Input: num1 = 25, num2 = 5
Output: LCM = 25

Input: num1 = 36, num2 = 72
Output: LCM = 72

There are two methods to find the LCM of two numbers, these are:

 

Table of Content

  • Using Mathematical Formula
  • Using Iteration

Similar Reads

Using Mathematical Formula

In this section, we use mathematical formula to calculate the LCM of two numbers. The LCM of two numbers is equal to the product of the two numbers divided by their Greatest Common Divisor (GCD)....

Using Iteration

...