Skip to content

Instantly share code, notes, and snippets.

@pascalduez
Last active April 12, 2019 08:35
Show Gist options
  • Save pascalduez/567df76107b64f4ee9a4 to your computer and use it in GitHub Desktop.
Save pascalduez/567df76107b64f4ee9a4 to your computer and use it in GitHub Desktop.
Prime number in Sass.
// ----
// Sass (v3.3.9)
// Compass (v1.0.0.alpha.20)
// ----
// Prime number
// https://en.wikipedia.org/wiki/Prime_number
// Returns whether `$n` is a prime number.
// ---
// @param {number} $n
// ---
// @return {bool}
@function is-prime($n) {
@if type-of($n) != number {
@warn "#{$n} is not a number for `is-prime`.";
@return null;
}
@if $n < 2 or $n != floor($n) {
@return false;
}
@if $n % 2 == 0 { @return $n == 2; }
@if $n % 3 == 0 { @return $n == 3; }
$i: 5;
$m: ceil(sqrt($n));
@while $i <= $m {
@if $n % $i == 0 or $n % ($i + 2) == 0 {
@return false;
}
$i: $i + 6;
}
@return true;
}
// Returns the factorial of a non-negative integer.
// ---
// @param {number} $n: a non-negative integer
// ---
// @return {number}
@function fact($n) {
@if $n < 0 or $n != floor($n) {
@warn "#{$n} is not a positive integer for `fact`.";
@return null;
}
$ret: 1;
@while $n > 0 {
$ret: $ret * $n;
$n: $n - 1;
}
@return $ret;
}
// Returns whether `$n` is a prime number.
// ---
// @param {number} $n
// ---
// @return {bool}
@function _is-prime($n) {
@if type-of($n) != number {
@warn "#{$n} is not a number for `is-prime`.";
@return null;
}
@if $n < 2 or $n != floor($n) {
@return false;
}
@return fact($n - 1) % $n == $n - 1;
}
// Tests
is-prime {
$fixture: (
7: true,
10: false,
37: true,
60: false,
373: true,
390: false,
1427: true,
1683: false,
7879: true,
7881: false,
// 2011: true,
// 9007199254740881: true
);
$tests: '';
@each $num, $bool in $fixture {
$pass: is-prime($num) == $bool;
$tests: $tests + if($pass, '✔ ', 'X ');
}
is-prime: $tests;
$tests: '';
@each $num, $bool in $fixture {
$pass: _is-prime($num) == $bool;
$tests: $tests + if($pass, '✔ ', 'X ');
}
_is-prime: $tests;
}
@charset "UTF-8";
is-prime {
is-prime: "✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ";
_is-prime: "✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment