Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Last active November 25, 2025 21:22
Show Gist options
  • Select an option

  • Save tatsuyax25/71177fcef6d17ab3a33da2b64fcbf9f7 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/71177fcef6d17ab3a33da2b64fcbf9f7 to your computer and use it in GitHub Desktop.
Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1. Return the length of n. If there is no such n, return -1. Note: n may not fit in a 64-bit sig
/**
* @param {number} k
* @return {number}
*/
var smallestRepunitDivByK = function(k) {
// Step 1: Handle impossible cases
// Any number made only of '1's is odd and not divisible by 2 or 5.
// So if k has a factor of 2 or 5, return -1 immediately.
if (k % 2 === 0 || k % 5 === 0) {
return -1;
}
// Step 2: Initialize variables
// remainder will track (current number % k) without building the full number.
// length will track how many '1's we've added so far.
let remainder = 0;
let length = 0;
// Step 3: Iterate until we find a remainder of 0
// At each step, we "append" another '1' to the number.
// new_remainder = (old_remainder * 10 + 1) % k
while (true) {
remainder = (remainder * 10 + 1) % k; // simulate appending '1'
length++; // increase the length of the repunit
// If remainder becomes 0, we found a number divisible by k
if (remainder === 0) {
return length;
}
// Safety check: If length exceeds k, we're cycling through remainders
// Without hitting 0, so no solution exists.
if (length > k) {
return -1;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment