﻿ CoffeeScript function: Compute the factors of a positive integers - w3resource # 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.

HTML Code:

``````<!DOCTYPE html>
<html>
<meta charset="utf-8">
<script src="//jashkenas.github.io/coffee-script/extras/coffee-script.js"></script>
<title>Compute the factors of a positive integer</title>
<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

console.log factors(15)
# [1,3,5,15]
console.log factors(16)
# [1,2,4,8,16]
console.log factors(17)
# [1,17]
``````

Sample Output:

```[1, 3, 5, 15]
[1, 2, 4, 8, 16]
[1, 17]
```

Live Demo:

See the Pen coffeescript-exercise-17 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus.

﻿