How to resolve the algorithm Primality by trial division step by step in the CMake programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Primality by trial division step by step in the CMake 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 CMake programming language
Source code in the cmake programming language
# Prime predicate: does n be a prime number? Sets var to true or false.
function(primep var n)
if(n GREATER 2)
math(EXPR odd "${n} % 2")
if(odd)
# n > 2 and n is odd.
set(factor 3)
# Loop for odd factors from 3, while factor <= n / factor.
math(EXPR quot "${n} / ${factor}")
while(NOT factor GREATER quot)
math(EXPR rp "${n} % ${factor}") # Trial division
if(NOT rp)
# factor divides n, so n is not prime.
set(${var} false PARENT_SCOPE)
return()
endif()
math(EXPR factor "${factor} + 2") # Next odd factor
math(EXPR quot "${n} / ${factor}")
endwhile(NOT factor GREATER quot)
# Loop found no factor, so n is prime.
set(${var} true PARENT_SCOPE)
else()
# n > 2 and n is even, so n is not prime.
set(${var} false PARENT_SCOPE)
endif(odd)
elseif(n EQUAL 2)
set(${var} true PARENT_SCOPE) # 2 is prime.
else()
set(${var} false PARENT_SCOPE) # n < 2 is not prime.
endif()
endfunction(primep)
# Quick example.
foreach(i -5 1 2 3 37 39)
primep(b ${i})
if(b)
message(STATUS "${i} is prime.")
else()
message(STATUS "${i} is _not_ prime.")
endif(b)
endforeach(i)
You may also check:How to resolve the algorithm Pig the dice game/Player step by step in the C++ programming language
You may also check:How to resolve the algorithm Binary strings step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Generate lower case ASCII alphabet step by step in the BASIC programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the Fexl programming language
You may also check:How to resolve the algorithm Aliquot sequence classifications step by step in the Nim programming language