How to test whether a number is prime

Perform test whether a number is a prime using command-line factor utility.

Check the number 809.

$ factor 809 | awk 'NF==2 { check="is a" } NF>2 { check="is not a" } { print $1 " " check " prime number" }'
809: is a prime number

Check the range of numbers between 30200 and 30225.

$ factor $(seq 30200 30225) | awk 'NF==2 { check="is a" } NF>2 { check="is not a" } { print $1 " " check " prime number" }'
30200: is not a prime number
30201: is not a prime number
30202: is not a prime number
30203: is a prime number
30204: is not a prime number
30205: is not a prime number
30206: is not a prime number
30207: is not a prime number
30208: is not a prime number
30209: is not a prime number
30210: is not a prime number
30211: is a prime number
30212: is not a prime number
30213: is not a prime number
30214: is not a prime number
30215: is not a prime number
30216: is not a prime number
30217: is not a prime number
30218: is not a prime number
30219: is not a prime number
30220: is not a prime number
30221: is not a prime number
30222: is not a prime number
30223: is a prime number
30224: is not a prime number
30225: is not a prime number

Display primes in the range of numbers between 100 and 120.

$ factor $(seq 100 120) | awk 'NF==2 { print substr($1, 1, length($1)-1) }'
101
103
107
109
113

Display primes in the range of numbers between 1 and 10 using for loop.

$ for i in $(seq 1 10); do factor $i | awk 'NF==2 { print substr($1, 1, length($1)-1) }';  done

This is the slowest solution and susceptible to the situation in which you can exceed command length, so I suggest to use previous ones.

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu