How to resolve the algorithm Attractive numbers step by step in the Lua programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Attractive numbers step by step in the Lua programming language

Table of Contents

Problem Statement

A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime.

The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime.

Show sequence items up to   120.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Attractive numbers step by step in the Lua programming language

Source code in the lua programming language

-- Returns true if x is prime, and false otherwise
function isPrime (x)
  if x < 2 then return false end
  if x < 4 then return true end
  if x % 2 == 0 then return false end
  for d = 3, math.sqrt(x), 2 do
    if x % d == 0 then return false end
  end
  return true
end

-- Compute the prime factors of n
function factors (n)
  local facList, divisor, count = {}, 1
  if n < 2 then return facList end
  while not isPrime(n) do
    while not isPrime(divisor) do divisor = divisor + 1 end
    count = 0
    while n % divisor == 0 do
      n = n / divisor
      table.insert(facList, divisor)
    end
    divisor = divisor + 1
    if n == 1 then return facList end
  end
  table.insert(facList, n)
  return facList
end

-- Main procedure
for i = 1, 120 do
  if isPrime(#factors(i)) then io.write(i .. "\t") end
end


  

You may also check:How to resolve the algorithm 24 game step by step in the Phix programming language
You may also check:How to resolve the algorithm Queue/Definition step by step in the Racket programming language
You may also check:How to resolve the algorithm Flipping bits game step by step in the Ada programming language
You may also check:How to resolve the algorithm Host introspection step by step in the Caché ObjectScript programming language
You may also check:How to resolve the algorithm Integer comparison step by step in the Oberon-2 programming language