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>
  <meta charset="utf-8">
  <title>JS Bin</title>


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

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.

Solve these problems:

Python: How to check whether a file exists using Python?

C#: Loops in c#

PHP: For each

SQL: JOIN using more than 5 tables

JavaScript: Blank Slide in Javascript Slideshow