Erlang Count Div
-module(count_div).
-export([count_div/3]).
count_div(A, B, K) ->
FirstDiv = case A rem K of
0 -> A;
R -> A + (K - R)
end,
LastDiv = B - (B rem K),
(LastDiv - FirstDiv) div K + 1.
This counts how many numbers in a range are divisible by K without looping through every value.
Go Count Div
func countDiv(a, b, k int) int {
firstDiv := a
if a%k != 0 {
firstDiv = a + (k - a%k)
}
lastDiv := b - b%k
return (lastDiv-firstDiv)/k + 1
}
This counts how many numbers in a range are divisible by K without looping through every value.
Haskell Count Div
countDiv :: Int -> Int -> Int -> Int
countDiv a b k = (lastDiv - firstDiv) `div` k + 1
where
firstDiv = if a `mod` k == 0 then a else a + (k - a `mod` k)
lastDiv = b - b `mod` k
This counts how many numbers in a range are divisible by K without looping through every value.
Java Count Div
public class Solution {
public static int countDiv(int a, int b, int k) {
int firstDiv = a % k == 0 ? a : a + (k - a % k);
int lastDiv = b - b % k;
return (lastDiv - firstDiv) / k + 1;
}
}
This counts how many numbers in a range are divisible by K without looping through every value.
Lisp Count Div
(defun count-div (a b k)
(let* ((first-div (if (zerop (mod a k)) a (+ a (- k (mod a k)))))
(last-div (- b (mod b k))))
(1+ (/ (- last-div first-div) k))))
This counts how many numbers in a range are divisible by K without looping through every value.
PHP Count Div
function countDiv(int $a, int $b, int $k): int
{
$firstDiv = $a % $k === 0 ? $a : $a + ($k - $a % $k);
$lastDiv = $b - $b % $k;
return ($lastDiv - $firstDiv) / $k + 1;
}
This counts how many numbers in a range are divisible by K without looping through every value.
Python Count Div
def count_div(a: int, b: int, k: int) -> int:
first_div = a if a % k == 0 else a + (k - a % k)
last_div = b - b % k
return (last_div - first_div) // k + 1
This counts how many numbers in a range are divisible by K without looping through every value.
Rust Count Div
fn count_div(a: i64, b: i64, k: i64) -> i64 {
let first_div = if a % k == 0 { a } else { a + (k - a % k) };
let last_div = b - b % k;
(last_div - first_div) / k + 1
}
This counts how many numbers in a range are divisible by K without looping through every value.
TypeScript Count Div
function countDiv(a: number, b: number, k: number): number {
const firstDiv = a % k === 0 ? a : a + (k - (a % k));
const lastDiv = b - (b % k);
return (lastDiv - firstDiv) / k + 1;
}
This counts how many numbers in a range are divisible by K without looping through every value.
Bash Count Factors
count_factors() {
local _n=$1
local _count=0 _i=1
while (( _i * _i < _n )); do
if (( _n % _i == 0 )); then
_count=$(( _count + 2 ))
fi
((_i++))
done
if (( _i * _i == _n )); then
((_count++))
fi
echo "$_count"
}
This checks divisors in pairs up to the square root, which keeps the work much smaller than testing every number.