w3resource

CoffeeScript function: Check a number is prime or not

CoffeeScript Function : Exercise-15 with Solution

Write a CoffeeScript function that accepts a number as a parameter and check the number is prime or not.

Note : A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

HTML Code :

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="//jashkenas.github.io/coffee-script/extras/coffee-script.js"></script>
  <title>Check a number is prime or not</title>
</head>
<body>

</body>
</html>

CoffeeScript Code :


test_prime = (n) ->
  if n == 1
    false
  else if n == 2
    true
  else
    x = 2
    while x < n
      if n % x == 0
        return false
      x++
    true
console.log test_prime(37)

Sample Output:

true

Live Demo :

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


Improve this sample solution and post your code through Disqus.