본문 바로가기
ICT

[PowerShell]9. Learning Projects - Finding prime numbers

by NeoSailer 2023. 5. 8.

A prime number is a whole number greater than 1 whose only factors are 1 and itself. For example, number 2 is a prime number because it can be divided by only 2 and 1. Howerver, since 4 can be divided by 1, 2 and 4, number 4 is not a prime number.

 

Let's write a script to figure out prime numbers within a certain number range. This can find all prime number and print them out. If we want to know all prime number in 10, then the script will print out all the prime numbers within 10 which are 2, 3, 5, 7.

 

First of all, we need get an number input from user. The input must be whole number so convert the input to int

try{
    $num = [int32](Read-Host "please input a number that you want to find prime number within")
}
catch
{
    "Please input number: $_"
}

 

Furthermore, number should be greater or equal than 2 because the least prime number is 2.

if($num -lt 2)
{
    Write-Host "Please input number greater than 1"
}

 

Now we need to use loop and if statement for deviding numbers from number itself -1 to 2 and if the number is not divided till the end of the loop then it should be prime number. To print out total number of prime number, declare a variable and count up if find a prime number.

 

$count = 0

for($num; $num -gt 1; $num--)
{    
    for($i=$num-1; $i -gt 0; $i--)
    {   
        if($i -eq 1)     
        {
            Write-Host $num
            $count++
        }
        if( ($num%$i) -eq 0)
        {
            break;
        }       
    }
}
Write-host "Found $count prime numbers!"

 

Now run the script and check if there is any bug.

 

Test #1. Input 10

please input a number that you want to find prime number within: 10
7
5
3
2
Found 4 prime numbers!

 

Test #2. Input 2

please input a number that you want to find prime number within: 2
2
Found 1 prime numbers!

 

Test #3. Input 1

please input a number that you want to find prime number within: 1
Please input number greater than 1
Found 0 prime numbers!

 

In case of that user input is less than 2, the script should stop at the point. Input "return" command in the if statement where checking user input and run again.

if($num -lt 2)
{
    Write-Host "Please input number greater than 1"
    return;
}
please input a number that you want to find prime number within: 1
Please input number greater than 1

 

Looks better. Now keep testing.

 

Test #4. input 100

please input a number that you want to find prime number within: 100
97
89
83
79
73
71
67
61
59
53
47
43
41
37
31
29
23
19
17
13
11
7
5
3
2
Found 25 prime numbers!

 

Test #5. Input 1000

 

please input a number that you want to find prime number within: 1000
997
991
983
...
5
3
2
Found 168 prime numbers!

All good. Double check the answer with ChatGPT. ChatGPT is low-quality which stops generating prim numbers at 541..

 

반응형

댓글