How can the code provided be refactored to improve readability and maintainability while still achieving the desired outcome of finding prime number pairs with a difference of 2?
The code can be refactored by breaking down the logic into smaller, more readable functions and using meaningful variable names. By doing so, the code will be easier to understand and maintain. Additionally, comments can be added to explain the purpose of each section of code.
function isPrime($num) {
if ($num < 2) {
return false;
}
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
return false;
}
}
return true;
}
function findPrimePairs($start, $end) {
$primePairs = [];
for ($i = $start; $i <= $end - 2; $i++) {
if (isPrime($i) && isPrime($i + 2)) {
$primePairs[] = [$i, $i + 2];
}
}
return $primePairs;
}
$start = 1;
$end = 100;
$primePairs = findPrimePairs($start, $end);
foreach ($primePairs as $pair) {
echo $pair[0] . ", " . $pair[1] . "\n";
}
Related Questions
- What are the potential benefits and drawbacks of using pre-existing scripts like PHP Nuke for website development?
- What are common pitfalls when using ADODB and addslashes in PHP?
- What best practices should PHP developers follow to handle and display special characters, such as Umlaute and ß, correctly in web applications, particularly when sending emails through platforms like Thunderbird?