
Understanding a PHP Program that Identifies Prime Numbers and Their Divisors
In this blog post, we will walk through a PHP program that determines prime numbers and their divisors (multiples) up to a given limit. The program is written in PHP, and its primary objective is to evaluate numbers from 1 up to a user-defined limit (in this case, 100), and for each number, determine if it's prime or show its divisors if it's not. Let's break it down step by step.
Lets create a function: getPrimeAndMultiples
The core of the program is the function getPrimeAndMultiples(int $limit): array. This function takes a single argument, $limit, which specifies the maximum number up to which we want to analyze numbers. The function returns an associative array containing the numbers and their respective labels (whether they are prime or their divisors).
Initializing the Result Array
The function begins by initializing an empty array $result that will eventually hold the numbers and their corresponding labels. This array will be populated as the loop iterates over the numbers up to $limit.
First Loop That is The Outer Loop
The outer for loop iterates through all numbers from 1 up to $limit. For each number $i, we are interested in identifying whether it is prime or finding its divisors.
Finding Divisors or Multiples
Inside the outer loop, there is another for loop that checks all numbers from 1 to $i to see if they are divisors of $i. This is done using the modulus operator (%). If the remainder of $i % $j equals 0, then $j is a divisor of $i, and it gets added to the $multiples array.
For example:
- If $i = 6, the divisors are 1, 2, 3, and 6.
- If $i = 10, the divisors are 1, 2, 5, and 10.
Checking if Number is Prime or Not
The program checks if a number has exactly two divisors, 1 and itself. If it does, the number is prime, and it's labeled as [PRIME]. If a number has more than two divisors, it lists them in a string and assigns that as the label.
For example:
- For $i = 6, the divisors are [1, 2, 3, 6].
- For $i = 5, it’s prime and labeled [PRIME].
Printing the result
Full Example Code
OUTPUT