How can you optimize the code provided to improve efficiency and readability in PHP?
The code can be optimized by using a more efficient way to check if a number is prime. One way to do this is by only checking divisibility up to the square root of the number. Additionally, we can improve readability by breaking down the logic into smaller, more understandable functions.
function isPrime($num){
if($num < 2){
return false;
}
for($i = 2; $i <= sqrt($num); $i++){
if($num % $i == 0){
return false;
}
}
return true;
}
function printPrimesInRange($start, $end){
for($i = $start; $i <= $end; $i++){
if(isPrime($i)){
echo $i . " ";
}
}
}
$start = 10;
$end = 50;
printPrimesInRange($start, $end);
Keywords
Related Questions
- What are some common challenges faced when generating HTML emails with PHP and how can they be overcome?
- What are the best practices for working with protected variables in PHP classes stored in the $_SESSION variable?
- What potential pitfalls should be considered when using PHP to process form data?