You are currently viewing the GMLscripts.com static mirror. Forum access and script submissions are not available through this mirror.

Invert GMLscripts.com

factor

Returns an array containing the prime factors of a given integer.

f = factor(   1);   //  [ ]
f = factor(   5);   //  [ 5 ]
f = factor(  12);   //  [ 2, 2, 3 ]
f = factor( 222);   //  [ 2, 3, 37 ]
f = factor( 256);   //  [ 2, 2, 2, 2, 2, 2, 2, 2 ]
f = factor(2222);   //  [ 2, 11, 101 ]
factor(num)
Returns an array containing the prime factors of a given integer.
COPY/// @func   factor(num)
///
/// @desc   Returns an array containing the prime factors of a given integer.
///
/// @param  {real}      number      positive integer
///
/// @return {array}     array of factors
///
/// GMLscripts.com/license

function factor(num)
{
    var factors = array_create(0);
    if (num >= 2) {
        var check = 2;
        while (sqr(check) <= num) {
              if (num mod check == 0) {
                  array_push(factors, check);
                  num = num div check;
              } else {
                  check += 1;
              }
        }
        if (num != 1) {
            array_push(factors, num);
        }
    }
    return factors;
}

Contributors: xot

GitHub: View · Commits · Blame · Raw