Backend Development
PHP Tutorial
PHP Loop Learning 9: Obtain the greatest common factor between two given numbersPHP Loop Learning 9: Obtain the greatest common factor between two given numbers
In the previous article "PHP Array Learning: Returning All Common Factors and the Greatest Common Factor between Given Two Numbers", we introduced a way to obtain all common factors of two integers. Factors, a method of finding the greatest common divisor. This time we will introduce to you a method of finding the greatest common divisor. Friends who are interested can learn about it~
In the previous article, we put all the factors of two integers in In two arrays, and then use the array_intersect() function to find the intersection of the two arrays, you can get an array containing all common factors; then use the max() function to calculate the maximum number in the intersection array, and you will get the greatest common factor.
Isn’t it a bit troublesome? We have to find out all the factors one by one, then calculate all the common factors, and finally find the greatest common divisor. Here's a simple and general method (can be used in other languages).
This time we do not use PHP built-in functions, but use if judgment statements and while loop statements to find the greatest common divisor between given two integers.
Implementation steps: There are two variables a and b
-
The first step: Make sure that large numbers are placed in a and decimals are placed in b.
This requires the use of an if statement to determine. If a
if ($a < $b) { //a < b,则交换两个数
$temp = $a;
$a = $b;
$b = $temp;
}Step 2: Find the remainder of
a/b, and assign the value to r
$r = $a % $b;
-
Step 3: Determine the remainder r Whether it is 0.
If
r=0, then b above is the greatest common divisor; ifr!=0, you need to assign the value of b to a, r Assign the value to b, continue to find the remainder of a/b, and determine whether the remainder r is 0. This requires the use of a loop (a while loop is used here):
while ($r != 0) {
$a = $b;
$b = $r;
$r = $a % $b;
}The fourth step: output the greatest common factor b.
Let’s take a look at the implementation code:
<?php
header("Content-type:text/html;charset=utf-8");
function gcd($a, $b) {
$a1 = $a;
$b1 = $b;
if ($a < $b)//a < b,则交换两个数
{
$temp = $a;
$a = $b;
$b = $temp;
}
$r = $a % $b;
while ($r != 0) {
$a = $b;
$b = $r;
$r = $a % $b;
}
echo "数$a1 和$b1 的最大公因数为: $b <br><br>";
}
gcd(30, 40);
gcd(12, 16);
gcd(15, 12);
?>Output result:

Okay, let’s talk We are here. If you want to know anything else, you can click this. → →php video tutorial
Recommended: 《PHP interview questions summary (collection)》
The above is the detailed content of PHP Loop Learning 9: Obtain the greatest common factor between two given numbers. For more information, please follow other related articles on the PHP Chinese website!
PHP: Efficiently merge multidimensional arrays to build structured datasetsAug 26, 2025 pm 06:03 PMThis article will dive into how multiple independent arrays (e.g., page ID, location, and priority) can be merged into a structured single array in PHP, where each element is an associative array containing related attributes. We will focus on the various implementations of using the array_map function combined with compact or array_combine, and discuss its flexibility and applicable scenarios, aiming to help developers process array data in a professional and efficient way.
Dynamically generate form fields based on user inputAug 26, 2025 pm 06:00 PMThis article describes how to use PHP to dynamically generate form fields based on user inputs in previous fields. With simple example code, it shows how to cycle through the corresponding number of text input boxes based on the number specified by the user and process the submitted data. Suitable for beginners to learn how to handle dynamic form generation in PHP.
Detailed explanation of phpMyAdmin multi-server configuration: Solve the problem of not displaying multiple database connections on the login interfaceAug 26, 2025 pm 05:57 PMThis tutorial aims to solve the problem that the phpMyAdmin login interface cannot display multiple database server options. By parsing the config.inc.php configuration file in detail, we will demonstrate how to use the officially recommended multi-host configuration method, use a loop structure to define multiple database connections, and ensure that all servers can be displayed normally and available for selection when phpMyAdmin login, thereby improving database management efficiency.
PHP Association Array Conversion: Dynamic Key Name Reconstructs Data StructureAug 26, 2025 pm 05:54 PMThis article describes how to use PHP to convert a specific associative array structure into another one that is more accessible and manipulated. The core is to recombinate the scattered data in the original array according to specific rules through loop traversal and dynamic key name assignment, and finally form a new associative array with name as keys, including ranking and amount information.
Laravel Eloquent Model Traversal: Solve Unexpected Output of Foreach LoopAug 26, 2025 pm 05:51 PMThis article aims to help developers understand the unexpected output that may occur when using foreach loops and provide solutions. Through the toArray() method, the Eloquent model can be converted into an array, thereby correctly traversing the properties and values of the model, avoiding accessing properties inside the model, and ensuring that the expected data is obtained.
Passing temporary arrays by reference in PHP: Principles, Methods and Best PracticesAug 26, 2025 pm 05:45 PMThis article explores the limitations of passing temporary arrays by reference in PHP, explains why passing temporary arrays directly causes errors, and provides a method to indirectly pass temporary array references through intermediate functions. At the same time, the applicable scenarios and potential problems of this practice are analyzed, and the principle that code readability and maintenance should be given priority in actual development.
PHP trim() function strategy for handling newlines in CSV file processingAug 26, 2025 pm 05:36 PMWhen using the PHP trim() function to process CSV files, if you find that the line end commas cannot be removed, the core reason is often the difference in line breaks between different operating systems. exploit(PHP_EOL, $csv) may fail to completely remove invisible line breaks at the end of the line, causing trim() to fail to recognize and remove the target character. The solution is to extend the character mask of trim() so that it processes commas, carriage return (\r) and line breaks (\n) at the same time to ensure thorough data cleaning.
Guide to Generation and Integration of X-FC-Nonce Request Header in PHPAug 26, 2025 pm 05:30 PMThis article details how to deal with the missing X-FC-Nonce request header in API requests in PHP. We will explore the role of X-FC-Nonce, provide a PHP function to generate a random number string Nonce that meets the requirements, and demonstrate how to properly integrate it into cURL requests to ensure the success and security of API calls.


Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.





