This is my script to check if a random number is prime or not :
[int]$nombre = Get-Random -Minimum 1 -Maximum 10
$nombre
$j=0
if($nombre -lt 2) { " $nombre n'est pas premier " }
else {
for($i=1; $i -le $nombre; $i++){
if( $nombre%$i -eq 0) {$j++}
}
if($j -eq 2 ) { "Le nombre est premier "}
else {"Ce nombre est premier"}
}
When I execute the script I get wrong results like 4 is a prime number. Any ideas to fixe it ? Thank you
I just wanted to improve the existing answer.
To me it is so obvious that I don't understand why hasn't anyone pointed out, it could simplify the whole process by skipping the for loop if the number is a square number, just add if ([math]::Sqrt{$number} -is [int]) {$prime = $false}
to the code before the loop, by definition square numbers are composite numbers, why no one noticed it?
Update: a better function based on the previous answer, it assigns $false to negative numbers, zero and fractions and non-numbers:
function Test-Prime {
param(
[Parameter(ValueFromPipeline=$true)]
$number
)
Process {
$prime = $true;
if ($number -isnot [int]) {$prime = $false}
elseif ($number -le 0) {$prime = $false}
else {
if ($number -eq 1) {
$prime = $false;
}
if ($number -gt 3) {
$sqrt = [math]::Sqrt($number);
if ($sqrt -is [int]) {$prime = $false}
else {
for($i = 2; $i -le $sqrt; $i++) {
if ($number % $i -eq 0) {
$prime = $false;
break;
}
}
}
}
}
return $prime;
}
}