Twisty's Tesseract

from Twisty's Mind come Twisted Products

isPrime

- Posted in Programming by

I've been trying my hand at more little programming snippets to help my math. Many I've written in Python, some in Linux 'bash' scripts (Bourne Again SHell).

Python isPrime

(I normally comment my code more, but comment markings in Android QPython3 seem to be "dicey.")

#qpy:3

import androidhelper
from math import sqrt, floor

def islpf(n):        # Lowest Prime Factor
    sqrtofn = int(sqrt(n))
    if (n%2==0):
        return 2
    else:
        i=3
        while i <= sqrtofn:
            if (n%i==0):
                return i
            else:
                i+=2
        return 0

try:
    droid = androidhelper.Android()
    line = droid.dialogGetInput()
    n = int(line.result)
    print("n =",n)
    s = "IsLPF for " + str(n) + " = " + str(islpf(n))
    print(s)
    droid.makeToast(s)
except:
    print("Please update to newest QPython version from (http://play.qpython.com/qrcode-python.html) to use this feature")

The result so far is a nice pop-up prompt to request the number to be tested, and a not-so-nice console window to print the result. A little more testing and playing about should provide a string to be popped back as a result.

Most people start a new language or platform with a "Hello, World" program. Me? I wanted to go a little further in trying out Android QPython3 for my first time. It already has sample code for running cool scripts from your phone, easily edited. (I ran "Say_Time", and got a response in Korean until I dug deeper into my settings.)

So the further step I wanted beyond "Hello, World" was a program to check numbers for prime factors. If it's prime, it shows no factor. If it's composite, it shows the Lowest Prime Factor (IsLPF?) which is the smallest/first factor it finds.

I'm sure the script will be further revised. This is just the first working draft. QPython3 has a lot of promise, but I may have to switch from the Goolge Play Store version to the more up-to-date GitHub branch. There was a case last month that it was taken off the store, but that might have changed. It seems too important a tool, writing fast script to run your own software on your smartphone.

Bash

Here below is a similar script written in Bash for Linux. It has an added bonus of supplying error codes that can be nested into other scripts as true/false tests. An error 0 is True in traditional Linux, although counterintuitive. An error 1 is common for a system error, e.g. keyboard entry mistakes. And for this script, an error 17 is the code I use to say 'the isPrime test came back False.' (This one is largely based on someone else's code.)

#!/bin/bash
# SCRIPT: prime3b.sh
# USAGE : ./prime3b.sh <Number to check >
# PURPOSE: Finds whether a given number is prime or not.

#####################################################################
#                       ARGUMENTS CHECKING                          #
#####################################################################

# If you are a beginner you can skip Arguments checking part.

if [ $# -ne 1 ]
then
    echo "Usage: isprime <number to check>"
    exit 1
fi

expr $1 + 1  &> /dev/null
if [ $? -ne 0 ]
then
    echo "Sorry, You supplied non numerical value"
    exit 1
fi

[ $1 -lt 2 ] && echo "Values < 2 are not prime numbers" && exit 1

#####################################################################
#                   MAIN PROGRAM STARTS HERE                        #
#####################################################################

num=$1
newnum=$((num-1))
i=1

while [ $((i*i)) -lt $newnum ]
do

  let i++           # you can also use i=`expr $i + 1`

  if [ $(((num/i)*i)) -eq $num ]
  then
      echo "$num is not a prime number"
      echo "since it is divisible by $i."
      exit 17
  fi

done

echo "$num is a prime number."
exit 0

I've got a similar snippet of bash code I wrote specifically to follow a trajectory in Collatz conjecture. That will be a separate article.