w3resource logo


CoffeeScript exercises

CoffeeScript function: Compute the factors of a positive integer

CoffeeScript Function : Exercise-17 with Solution

Write a CoffeeScript function to compute the factors of a positive integer.

Solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>

</body>
</html>

CoffeeScript Code :

factors = (n) ->
  num_factors = []
  i = undefined
  i = 1
  while i <= Math.floor(Math.sqrt(n))
    if n % i == 0
      num_factors.push i
      if n / i != i
        num_factors.push n / i
    i += 1
  num_factors.sort (x, y) ->
    x - y
  # numeric sort
  num_factors

alert factors(15)
# [1,3,5,15] 
alert factors(16)
# [1,2,4,8,16] 
alert factors(17)
# [1,17]

Live Demo :

JS Bin on jsbin.com

Post your code through Disqus :



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number