CHEFMGXPRIME - Editorial

Problem Link - Chef and Magical Steps in Number theory

Problem Statement:

Chef needs to climb from the Xth stair to the Yth stair in the minimum number of steps. He can either climb one stair at a time or climb two stairs if the destination stair (X+2) is a prime number.
Help Chef reach the Yth stair from the Xth stair in minimum number of steps.

Approach:

  • Chef can move from stair X to stair Y in two ways:
  1. Climbing one stair at a time: Chef moves from i to i+1.
  2. Climbing two stairs at a time: Chef can only do this if the final stair position he lands on (i.e., X+2) is a prime number.
  • To determine the minimum number of steps Chef can take to reach from stair X to stair Y, we need to understand how the ability to skip stairs (by climbing two at a time) influences the overall step count.
  • Counting Non-Primes: By computing the number of non-prime stairs between X and Y, we can derive the minimum number of steps Chef must take.

Why are we calculating non-primes:

  • Chef can only skip one stair if the resulting stair is prime. Thus, the number of non-prime stairs in the range directly affects how Chef can progress.
  • If a stair is non-prime, Chef can only move to it by climbing one stair at a time.
  • The more non-prime stairs there are, the fewer opportunities Chef has to jump by two stairs.
  • The formula used to compute the minimum number of steps is:
    Steps = YX − (count of primes between X+1 and Y)
    • Y−X: Represents the total distance Chef needs to cover in terms of stairs.
    • (count of primes between X+1 and Y): Represents the maximum number of two-stair jumps Chef can make. Each prime number allows Chef to skip an additional stair, thus reducing the total number of steps he needs to take.

By subtracting the count of prime stairs from the total distance, we effectively compute the number of individual steps Chef must take due to the constraints imposed by non-prime stairs.

Complexity:

  • Time Complexity: The Sieve of Eratosthenes runs in O(n log ⁡log ⁡n) for precomputation.
  • Space Complexity: The space used is O(n) for computing prime numbers and total prime numbers in a given range.