How to resolve the algorithm Primality by trial division step by step in the UNIX Shell programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Primality by trial division step by step in the UNIX Shell programming language

Table of Contents

Problem Statement

Write a boolean function that tells whether a given integer is prime.

Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Primality by trial division step by step in the UNIX Shell programming language

Source code in the unix programming language

function primep {
	typeset n=$1 p=3
	(( n == 2 )) && return 0	# 2 is prime.
	(( n & 1 )) || return 1		# Other evens are not prime.
	(( n >= 3 )) || return 1

	# Loop for odd p from 3 to sqrt(n).
	# Comparing p * p <= n can overflow.
	while (( p <= n / p )); do
		# If p divides n, then n is not prime.
		(( n % p )) || return 1
		(( p += 2 ))
	done
	return 0	# Yes, n is prime.
}

primep() {
	set -- "$1" 3
	test "$1" -eq 2 && return 0		# 2 is prime.
	expr "$1" \% 2 >/dev/null || return 1	# Other evens are not prime.
	test "$1" -ge 3 || return 1

	# Loop for odd p from 3 to sqrt(n).
	# Comparing p * p <= n can overflow. We use p <= n / p.
	while expr $2 \<= "$1" / $2 >/dev/null; do
		# If p divides n, then n is not prime.
		expr "$1" % $2 >/dev/null || return 1
		set -- "$1" `expr $2 + 2`
	done
	return 0	# Yes, n is prime.
}

  

You may also check:How to resolve the algorithm Number reversal game step by step in the Oforth programming language
You may also check:How to resolve the algorithm Play recorded sounds step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Copy a string step by step in the D programming language
You may also check:How to resolve the algorithm Hickerson series of almost integers step by step in the REXX programming language
You may also check:How to resolve the algorithm Balanced ternary step by step in the Ada programming language