Solution 2 for Scaler Topics Fortnightly Contest - 27
Boys love Shoes
This article is part of the Scaler Topics Fortnightly Contest - 27
Build an AI-First Career, Master the Complete Skillset
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
AI Forward Deployed Engineer Program
Full-stack engineering, production AI and client-facing consulting
+1000 moreSolution Approach
First, it’s important to observe that in order to maintain a certain number of options indefinitely, this number must be at least 2 and divide A. Let’s identify the smallest such number, denoted as d. If d is less than or equal to B, we can consistently vote for the first d options evenly. However, if d is greater than B, each round would inevitably reduce the number of remaining options until only one is left. Therefore, the answer is 1 if and only if d is greater than B.
To efficiently find the value of d, we recognize that d is the smallest divisor of A, excluding 1. We can determine d through various methods, one of which involves checking all numbers from 2 up to the square root of A. If no divisors are found, then A is a prime number, and d is equal to A. This approach results in a solution with a time complexity of O(sqrt(A)).
While the previous solution is effective, it may not be fast enough in certain languages like Python. To optimize it, we can employ the sieve of Eratosthenes to find the smallest divisor, leading to a pre-computation time complexity of O(A log A) or even faster, with O(1) time complexity to answer each test case
Time complexity
C++ Implementation
Java Implementation
How Scaler Transformed Careers in Different Fields
Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.