code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

507 Perfect Number

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/*
 * We define the Perfect Number is a positive integer that is equal to the
 * sum of all its positive divisors except itself.
 *
 * Now, given an integer n, write a function that returns true when it is
 * a perfect number and false when it is not.
 *
 * Example:
 * Input: 28
 * Output: True
 * Explanation: 28 = 1 + 2 + 4 + 7 + 14
 */

function perfectNumber(value) {
  if (value < 3) return false
  let divisor = 2
  let sum = 0
  while (divisor <= Math.sqrt(value)) {
    if (value % divisor === 0) {
      sum += divisor + (value/divisor)
    }
    divisor++
  }
  sum++
  return sum === value
}

test('perfect Number', () => {
  expect(perfectNumber(28)).toEqual(true)
})

Created 2020-04-11T20:57:31+00:00 · Edit