How to resolve the algorithm Factors of an integer step by step in the Groovy programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Factors of an integer step by step in the Groovy programming language

Table of Contents

Problem Statement

Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Factors of an integer step by step in the Groovy programming language

Source code in the groovy programming language

def factorize = { long target -> 

    if (target == 1) return [1L]

    if (target < 4) return [1L, target]

    def targetSqrt = Math.sqrt(target)
    def lowfactors = (2L..targetSqrt).grep { (target % it) == 0 }
    if (lowfactors == []) return [1L, target]
    def nhalf = lowfactors.size() - ((lowfactors[-1] == targetSqrt) ? 1 : 0)
    
    [1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target]
}


((1..30) + [333333]).each { println ([number:it, factors:factorize(it)]) }


  

You may also check:How to resolve the algorithm Queue/Definition step by step in the Elisa programming language
You may also check:How to resolve the algorithm Semiprime step by step in the Elixir programming language
You may also check:How to resolve the algorithm Caesar cipher step by step in the GFA Basic programming language
You may also check:How to resolve the algorithm Perfect totient numbers step by step in the Sidef programming language
You may also check:How to resolve the algorithm Compare length of two strings step by step in the Racket programming language