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>
<head>
  <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>
</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

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/coffeescript-exercises/coffeescript-exercise-17.php