Leetcode 2549. Count Distinct Numbers on Board
2549. Count Distinct Numbers on Board
You are given a positive integer n
representing the initial number written on a board. Every day, for any number x
written on the board, you write down every factor of x - 1
on the board. This process continues until no more new numbers can be written on the board. You need to determine how many distinct numbers will be present on the board at the end.
x - 1
where x
is the current number written on the board?
x - 1
for the numbers currently on the board.n
?
1 <= n <= 10^9
considering the problem statement described.n
on the board initially?
n
and based on the factors of x - 1
, other numbers are added to the board.n
on the board and a set to hold distinct numbers.x
currently on the board, add all factors of x - 1
to the set.x - 1
, find all its factors efficiently using integer factorization.Here’s a Java implementation to determine the number of distinct numbers on the board:
import java.util.HashSet;
import java.util.Set;
public class CountDistinctNumbersOnBoard {
public static int countDistinctNumbers(int n) {
Set<Integer> board = new HashSet<>();
board.add(n);
while (true) {
Set<Integer> newNumbers = new HashSet<>();
for (int number : board) {
if (number > 1) {
int value = number - 1;
for (int i = 1; i * i <= value; i++) {
if (value % i == 0) {
newNumbers.add(i);
if (i != value / i) {
newNumbers.add(value / i);
}
}
}
}
}
// If no new numbers are added, we are done
if (board.containsAll(newNumbers)) {
break;
}
board.addAll(newNumbers);
}
return board.size();
}
public static void main(String[] args) {
int n = 12; // example input, can be changed
System.out.println(countDistinctNumbers(n));
}
}
O(sqrt(m))
for a number m
.n <= 10^9
.Given the above considerations, the time complexity can be high for larger values of n
, but steps are taken to ensure only distinct numbers are processed.
By executing and understanding the logic, you should be able to understand how many distinct numbers will eventually be on the board.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?