Created
March 25, 2016 18:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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