Skip to content

Instantly share code, notes, and snippets.

@balamark
Created July 18, 2016 00:42
Show Gist options
  • Save balamark/61044d27a2a60b6006d757e04d3e58d1 to your computer and use it in GitHub Desktop.
Save balamark/61044d27a2a60b6006d757e04d3e58d1 to your computer and use it in GitHub Desktop.
editorial
// - number theory: r = (r * p10 + number) % k
// - 32bit int overflow because of multiplication
// - cycle dectection: cyclen length < k, only need to iterate k times
public int getSmallest(int number, int k) {
long r = number % k, n = number, p10 = 1;
while (n > 0) {
n /= 10;
p10 *= 10;
}
for (int i = 1; i <= k; ++i) {
if (r == 0) return i;
r = (r * p10 + number) % k;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment