#!/bin/bash

maxint=9223372036854775807
root=3037000499
destination=255

rm -f prime.list prime.hex.list prime.dec.list

SECONDS=0

echo "01 1" >> prime.list
echo "02 2" >> prime.list
echo "03 3" >> prime.list
echo "05 5" >> prime.list
echo "07 7" >> prime.list

for ((n=3; n<$((destination+1)); n++)); do
  #echo -n "Number $n > "
  sqrt=$(echo "scale=0; sqrt($n)" | bc)
  if [[ $((sqrt*sqrt)) != $n ]]; then
#  echo "$n > $p > $sqrt"
#  sleep 1s
    for ((p=2; p<$sqrt; p++)); do
      #echo "$n > $p > $sqrt"
      #sleep 1s
      if [[ $((n%p)) == 0 ]] && [[ $p != $((sqrt-1)) ]]; then
        #echo "NOT PRIME"
        p=$sqrt
      elif [[ $((n%p)) != 0 ]] && [[ $p == $((sqrt-1)) ]]; then
        clear
        hex=$(printf "%02X" "$n")
        echo "Number $n of $destination is PRIME [$((n*100/destination)) %]"
        #echo "$n" >> prime.dec.list
        #echo "$hex" >> prime.hex.list
        echo "$hex $n" >> prime.list
        rate=$((SECONDS*1000000/n))
        estsec=$((rate*destination/1000000))
        remsec=$((estsec-SECONDS))
        found=$(cat prime.list | wc -l)
        echo "Running Time: $((SECONDS/86400)) days, $(((SECONDS%86400)/3600)) hours, $(((SECONDS%3600)/60)) minutes and $(((SECONDS%60))) seconds..."
        echo "Remaining Time: $((remsec/86400)) days, $(((remsec%86400)/3600)) hours, $(((remsec%3600)/60)) minutes and $(((remsec%60))) seconds..."
        echo "Found $found PRIME numbers at an average rate of $((found/(SECONDS+1))) per second..."
      fi
    done
  fi
done
