Skip to content

Instantly share code, notes, and snippets.

@Liblor
Created March 25, 2016 18:51
Show Gist options
  • Save Liblor/a09e2608c3c20820a931 to your computer and use it in GitHub Desktop.
Save Liblor/a09e2608c3c20820a931 to your computer and use it in GitHub Desktop.
A is_prime function in bash script using trail division, thus not very fast and efficient.
#!/usr/bin/env bash
#
# Author: Liblor
# Date: 16.03.2016
# License: Creative Commons Attribution License (CC BY 4.0)
#
#
# A is_prime function in bash script using trail division,
# thus not very fast and efficient.
#
function is_prime {
local maxi=$(echo "sqrt( $1 )+1" | bc)
local i=0;
if [ $1 -lt 2 ]; then
return 1
fi
if [ $1 -eq 2 ]; then
return 0
fi
if [ $1 -eq 3 ]; then
return 0
fi
if [ $(($1%2)) -eq 0 ]; then
return 1
fi
for i in $(seq 3 $maxi); do
if [ $(($1%i)) -eq 0 ]; then
return 1
fi
done
return 0
}
for i in {1..50}; do
if is_prime $i; then
echo "$i is a prime"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment