Count Distinct Numbers on Board - Problem

You are given a positive integer n that is initially placed on a board. Every day, for 109 days, you perform the following procedure:

  • For each number x present on the board, find all numbers 1 <= i <= n such that x % i == 1.
  • Then, place those numbers on the board.

Return the number of distinct integers present on the board after 109 days have elapsed.

Note:

  • Once a number is placed on the board, it will remain on it until the end.
  • % stands for the modulo operation. For example, 14 % 3 is 2.

Input & Output

Example 1 — Small Number
$ Input: n = 2
Output: 1
💡 Note: Start with {2}. Check 2 % i = 1 for i ∈ [1,2]. No valid i exists since 2 % 1 = 0 and 2 % 2 = 0. No new numbers added, so answer is 1.
Example 2 — Basic Case
$ Input: n = 4
Output: 3
💡 Note: Start {4} → 4%3=1 so add 3 → {4,3} → 3%2=1 so add 2 → {4,3,2} → no new additions. Final count: 3.
Example 3 — Larger Input
$ Input: n = 6
Output: 5
💡 Note: Process: {6} → add 5 (6%5=1) → {6,5} → add 2,4 (5%2=1,5%4=1) → {6,5,2,4} → add 3 (4%3=1) → {6,5,2,4,3} → no more additions. Count: 5.

Constraints

  • 1 ≤ n ≤ 1000

Visualization

Tap to expand
Count Distinct Numbers on Board INPUT Initial Board n = 2 Days to simulate: 10^9 days Input Parameters n = 2 Single positive integer Rule: x % i == 1 Add i to board if true ALGORITHM STEPS 1 Check Base Case If n == 1, return 1 (only 1 stays on board) 2 Key Observation For any x on board: x % (x-1) == 1 always 3 Early Termination All numbers 2 to n will appear eventually 4 Return Result Answer = n - 1 (numbers 2 to n) Trace for n = 2 n = 2, so n == 1? No Check: 2 % 1 == 1? No No new numbers added Result: n-1 = 2-1 = 1 FINAL RESULT Board After 10^9 Days 2 Distinct Count 1 OK - Verified! For n = 2: Only number 2 remains Count = 2 - 1 = 1 Key Insight: Early Termination Optimization For any number x greater than 1 on the board, x % (x-1) always equals 1. This means (x-1) will be added. Eventually, all numbers from 2 to n will appear. For n greater than 1, answer is simply n-1. For n = 1, only 1 exists (no valid i where 1 % i == 1), so answer is 1. Time complexity: O(1). TutorialsPoint - Count Distinct Numbers on Board | Early Termination Optimization
Asked in
Google 25 Microsoft 15
31.2K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen