C++ Solution | Duty Roster

C++ Solution | Duty Roster

๐Ÿ“ Problem Description

Little Yang and Little Hong are on duty, responsible for cleaning the classroom. Little Yang is on duty every day, and Little Hong is on duty every day. Today they are both on duty together, how many days will it take for them to be on duty again on the same day?

๐Ÿ’ก Thought Analysis

  • Cycle Pattern: The number of days until they are on duty again on the same day is to find the smallest number that can be divisible by both and .
  • Brute Force Enumeration Method: Start from the larger number and try each number until finding one that can be divided by both numbers.

๐Ÿ” Algorithm Implementation

#include <iostream>
using namespace std;

int main(int argc, char const *argv[])
{
    int m, n;
    cin >> m >> n;

    // Start from the larger number and increment until finding a number divisible by both
    int ans = m > n ? m : n;
    while (ans % m != 0 || ans % n != 0)
        ans++;
    cout << ans << endl;
    return 0;
}

๐Ÿง‘ Code Explanation

  1. Input (Little Yang’s cycle), (Little Hong’s cycle).
  2. Start from the larger number and try each number until finding one that is divisible by both and .
  3. Output the result.

๐Ÿงช Test Cases

Input Output
3 4 12
5 7 35
6 8 24
9 12 36

๐Ÿ“Œ Summary

This problem tests how to find the number of days until both are on duty again on the same day. The brute force enumeration method is simple and easy to understand, suitable for beginners to grasp cycle problems. Have you learned it? Feel free to leave a comment for discussion!

Leave a Comment