While loops
Programming Fundamentals DSA practice problem on Onlearn.
Difficulty: easy.
Topics: Understanding While Loops in Programming: Structure, Use Cases, Termination, and Optimization, Loops, Conditional Statements, Optimization, Basic Arithmetic, Time Complexity, Space Complexity, mathematical operations, general programming, optimization, While Loop, Loop Termination, Loop Control Statements, Factorials, Algorithm Optimization.
Cumulative Product with Early Termination You are tasked with simulating a process of cumulative multiplication. You start with a product value of 1. In each step, you multiply the current product by a consecutive integer, beginning from 1. This process continues as long as the current integer to multiply by does not exceed N. However, there is an important condition: if at any point the product becomes greater than or equal to a given threshold K, you must immediately stop the multiplication process and output the product calculated just before or at that point. If the entire process completes (i.e., you have multiplied by all integers up to N) and the product never reached K, then you should output the final product. Input The input consists of two positive integers, N and K, on a single line. Output Print a single integer representing the final calculated product. Constraints 1 <= N <= 20 1 <= K <= 10^18 Sample Test Case 1 Input: Output: Explanation: Initial product = 1. 1. Multiply by 1: product = 1 1 = 1. (1 < 20) 2. Multiply by 2: product = 1 2 = 2. (2 < 20) 3. Multiply by 3: product = 2 3 = 6. (6 < 20) 4. Multiply by 4: product = 6 4 = 24. (24 = 20). Stop. Output: 24. Sample Test Case 2 Input: Output: Explanation: Initial product = 1. 1. Multiply by 1: product = 1. 2. Multiply by 2: product = 2. 3. Multiply by 3: product = 6. 4. Multiply by 4: product = 24. Current number (5) N (4). Loop terminates. The final product (24) is less than K (1000). Output 24.