http://codingdojang.com/scode/539?answer_mode=hide

var assert = require('assert')
/**
 * 자기 자신을 제외한 모든 양의 약수들의 합이 자기 자신이 되는 자연수를 완전수라고 한다. 
 * 예를 들면, 6과 28은 완전수이다. 6 = 1 + 2 + 3 // 1, 2, 3은 6의 약수
 * 28 = 1 + 2 + 4 + 7 + 14 // 1, 2, 4, 7, 14는 각각 28의 약수
 *
 * 입력으로 자연수 N을 받고, 출력으로 N이하의 모든 완전수를 출력하는 코드를 작성하라.
 */

function divisorWithoutSelf(n) {
  var divisors = []
  for (var i = 1; i < n; i++) {
    if (n % i === 0) {
      divisors.push(i)
    } 
  }
  return divisors
}

function sumOfList(list) {
  return list.reduce((a, b) => (a + b), 0)
}

function isPerfectNumber(n) {
  return n === sumOfList(divisorWithoutSelf(n))
}

function perfectNumbers(n) {
  var numbers = []

  for (var i = 2; i <= n; i++) {
    if (isPerfectNumber(i)) {
      numbers.push(i)
    }
  }
  return numbers
}

describe('get perfect numbers', () => {
  it('divisors without self', () => {
    assert.deepEqual(divisorWithoutSelf(6), [1, 2, 3])
  })
  it('sum of list', () => {
    assert.equal(sumOfList([1, 2, 3]), 6)
  })
  it('is perfect number', () => {
    assert.equal(isPerfectNumber(6), true)
  })
  it('perfect numbers', () => {
    assert.deepEqual(perfectNumbers(500), [6, 28, 496])
  })
})



 


'coding' 카테고리의 다른 글

에잇퍼센트 면접 문제  (0) 2017.02.03

https://brunch.co.kr/@sunghokimnxag/5

재미로 풀어본 면접문제. 하지만 면접문제로 좋은 문제인지는 모르겠다.


var assert = require('assert')
/**
 * 1,2,3,4,5,6,[7],6,5,4,3,2,1,[0],1,2,[3]
 * n번째 숫자가 7의 배수이거나 7이란 숫자를 포함할 시에 방향을 바꾼다.
 * for loop 또는 array를 쓰지 말 것.
 * assignment 를 쓰지 말 것. 즉, 변수 할당을 하지 말 것.
 * String을 쓰지 말것. 
 * 
 */
function pingpong(max, index, value, add) {
  function direction(add) {
    if (index % 7 === 0 || /7/.test(index)) {
      return add * -1
 
    } else {
      return add
    }
  }
  if (index === max) {
    return value
 
  } else {
    return pingpong(
      max, 
      index ? index + 1 : 1, 
      value !== undefined ? value + direction(add ? add : 1) : 1,
      direction(add ? add : 1)
    ) 
  }
}
 
describe('pingpong', () => {
  it('8번째 숫자는 6', () => {
    assert.equal(pingpong(8), 6)
  })
})

'coding' 카테고리의 다른 글

완전수 구하기  (0) 2017.04.02

+ Recent posts