The numbering of the exercise is indicative of the level of difficulty, from the simplest to the most complicated. If you have any comments, questions or suggestions: write to us at info @bloginnovazione.it
A prime number is an integer greater than 1 whose only divisors are 1 and itself, such as -2, 3, 5, 7, 11, etc.
For example, 17 is a prime number because it is only divisible by 1 and 17. However, 18 is not a prime number because it is divisible by 2, 3, 6, 9 and the number itself. These are several ways to print a prime number between 1 and 100 in the PHP programming language.
The following code prints a list of prime numbers between 1 and 50 (that is, numbers that are not divisible by anything other than 1 or the number itself) using a while loop.
<?php
$limit = 50;
$init = 2;
while(TRUE)
{
$div = 2;
if($init > $limit)
{
break;
}
while(TRUE)
{
if($div > sqrt($init))
{
echo $init." ";
break;
}
if($init % $div == 0)
{
break;
}
$div = $div + 1;
}
$init = $init + 1;
}
In the solution we have two while loops. The inner while loop tests with every possible divisor. If the inner loop finds a divisor, the number isn't prime, so it stops without printing anything, and if the test goes all the way to the square root of the number, we can assume the number is prime. The outer loop runs through all numbers between 1 and 50. This loop is broken when we have reached the breaking point of the numbers to be tested.
BlogInnovazione.it
Developing fine motor skills through coloring prepares children for more complex skills like writing. To color…
The naval sector is a true global economic power, which has navigated towards a 150 billion market...
Last Monday, the Financial Times announced a deal with OpenAI. FT licenses its world-class journalism…
Millions of people pay for streaming services, paying monthly subscription fees. It is common opinion that you…