Need php code for 1) Create a function that checks if an integer n is a prime (r
ID: 3551311 • Letter: N
Question
Need php code for
1) Create a function that checks if an integer n is a prime (returns true if the integer is prime and false otherwise). In the body of your page create a loop that uses this function to check and display all primes in a range from 1 to 100.
2) Create a function GeneratePassword which accepts two arguments, an integer and a character string consisting of letters (a-z) and digits (0-9).
When GeneratePassword(5,'abc0123') is called, it should return a random string of 5 characters taken from 'abc0123'. For Example : GeneratePassword(7,'abczxc012394') could return any of the following outputs : 2c00acb 2c23z93 030b2a4
In the body of your page generate three different calls to this function using a different numeric value and text string and display the results.
Explanation / Answer
<?php
function isPrime($num)
{
if($num == 1)
return false;
if($num == 2)
return true;
if($num % 2 == 0)//all the cases multiple of two excluded here now we have to check only odd numbers
return false;
//after ceil(sqrt($num) the numbers started to multiple of lesser number than ceil(sqrt($num). So just check till ceil(sqrt($num) will be fine and take less time.
for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2)
{
if($num % $i == 0)
return false;
}
return true;
}
function GeneratePassword($n,$domain)
{
$len = strlen($domain);
$pass = str_repeat("",$n);
for($i=0;$i<$n;$i++)
{
$randomPassChar = $domain[rand(0, $len-1)];
$pass[$i]=$randomPassChar;
}
return $pass;
}
//for web page
echo "Prime number exist between 1 to 100<br/>";
for($i=1;$i<=100;$i++)
{
if(isPrime($i))
{
echo $i." is prime<br/>";
}
}
//for pass generator
echo "password generated of length 5 from 'abc123' : ".GeneratePassword(5,"abc123")."<br/>";
echo "password generated of length 7 from 'xyzabc123' : ".GeneratePassword(7,"xyzabc123")."<br/>";
echo "password generated of length 9 from 'abcdef789' : ".GeneratePassword(9,"abcdef789")."<br/>";
echo "password generated of length 5 from '12345xyz' : ".GeneratePassword(5,"12345xyz")."<br/>";
?>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.