Home > Mobile >  How To Find Multiplication Factors of a negative number
How To Find Multiplication Factors of a negative number

Time:10-30

I wanna find the factors of a negative number in multiplication

Somethings not right on my method, it only works on positive numbers not negative

I have this and it did not work with negative numbers

function factorMul(num) {

  let tryThis1 = Math.floor(

    Math.random() * (num - 1   1)   1

  )

  let tryThis2 = Math.floor(

    Math.random() * (num - 1   1)   1

  )

  if(Math.floor(tryThis1 * tryThis2) !== num) return factorMul(num)

  return [tryThis1, tryThis2]

}

When i tried it with negative numbers i got maximum call stack size

Thanks to Amirhossein Sefati for making me understand what i need to do

I have this code and now it works!!

function factorMul(num) {
  if(String(num).startsWith('-')) {
    let positive = parseInt(String(num).replaceAll('-', ''))
    let factors = factorMul(positive)

    let change = Math.floor(
      Math.random() * (2 - 1   1)   1
    )-1
      
    factors[change] = parseInt("-" factors[change])

    return factors
  }
  
  let tryThis1 = Math.floor(
    Math.random() * (num - 0   1)   1
  )
  let tryThis2 = Math.floor(
    Math.random() * (num - 0   1)   1
  )

  if(Math.floor(tryThis1 * tryThis2) !== num) {
    return factorMul(num)
  }

  return [tryThis1, tryThis2]
}

CodePudding user response:

Find Multiplication Factors of a negative number:

  • Essentially, to factor a negative number, find all of its positive factors, then duplicate them and write a negative sign in front of the duplicates. For instance, the positive factors of −3 are 1 and 3. Duplicating them produces 1, 3, 1, 3; writing a negative sign before the duplicates produces 1, 3, −1, −3, which are all of the factors of −3.

So, in your code, just check if the number passed is negative, if it was, make it positive, then when it is ready to return the values, do the hint above.

  • Related