1

I'm trying to "traduce" from Python (What is the best algorithm for checking if a number is prime?) to Shell Script. This is my idea (probably very silly code):

#!/bin/bash
prime (){
i=5
w=2
while [ `echo "$i*$i" | bc -l ` -le $n ]
    do
      if [ n % i -eq 0 ]
        then echo "$n is not prime"
      else
        i = i + w
        w = 6 - w
        echo "$n is prime"
    fi
done
}
echo "Test for knowing if a number is prime or not."
sleep 2
echo "Enter the number"
read n
if [ $n -eq 1 ]
   then echo "Number 1 is not prime"
elif [ $n -eq 2 ]
   then echo "Number two is prime"
elif [ $n -eq 3 ]
   then echo "Number three is prime"
else
   prime
fi

The problem is when i put any other number (4, 5, 6, ...) the program doesn't return back if $n is prime or not. If anyone can help me, I will be very grateful.

Community
  • 1
  • 1
Carlos
  • 31
  • 2

2 Answers2

1

If you have access to factor from GNU core utilities:

f=$(factor 11 | wc -w); [[ $f -eq 2 ]] && echo prime || echo not prime

Output:

prime

f=$(factor 6 | wc -w); [[ $f -eq 2 ]] && echo prime || echo not prime

Output:

not prime
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • I'm so sorry, I didn't understand. What is factor? – Carlos Dec 06 '14 at 19:45
  • `factor` is part of GNU core utilities and made for factorization/factoring. See: http://www.gnu.org/software/coreutils/manual/html_node/factor-invocation.html#factor-invocation – Cyrus Dec 06 '14 at 19:51
0

There were so many problems in the code. The main problem was that you did not implement the code given in that link properly. You did not check the divisibility by 2,3 (3rd and 4th conditions) so the code will just exit for numbers less that 25, so I added those conditions. Further there were errors in the if statement, assignments etc., Please tell if you want any further clarifications.

Here is the corrected code

#!/bin/bash
prime (){
i=5
w=2
isprime=1
while [ `echo "$i*$i" | bc -l ` -le $n ]
    do
      if [ $((n % i)) -eq 0 ]
        then
        isprime=0
        break
      else
        i=$(($i+$w))
        w=$((6-$w))
    fi
done
if [ $isprime -eq 0 ]
  then echo "$n is not a prime"
else
  echo "$n is a prime"
fi
return 0
}
echo "Test for knowing if a number is prime or not."
echo "Enter the number"
read n
if [ $n -eq 1 ]
   then echo "Number 1 is not prime"
elif [ $n -eq 2 ]
   then echo "Number two is prime"
elif [ $n -eq 3 ]
   then echo "Number three is prime"
elif [ $((n % 2)) -eq 0 ]
   then echo "$n is not a prime"
elif [ $((n % 3)) -eq 0 ]
   then echo "$n is not a prime"
else
   prime
fi

Hope this helps.