AtCoder Beginner Contest 165 A Problem "We Love Golf" Explanation (Python3, C ++, Java)

This is Rute.

AtCoder Beginner Contest 165 A I will explain the problem "We Love Golf".

Problem URL: https://atcoder.jp/contests/abc165/tasks/abc165_a

Problem summary

(The problem statement is briefly expressed as follows) Determine if there is a multiple of $ K $ in an integer greater than or equal to $ A $ and less than or equal to $ B $. 'OK' if it exists If it does not exist, output 'NG'.

Constraint

・ All inputs are integers ・ $ 1 \ leq A \ leq B \ leq 1000 $ ・ $ 1 \ leq K \ leq 1000 $

Solution 1 (loop)

The first solution that comes to mind for this problem is to use a for statement loop </ b> to find out if the range of $ (A, B) $ contains multiples of $ K $. Thing. The amount of calculation is $ O (B) $.

Solution 2 (find the maximum multiple of K less than or equal to B)

The problem statement can be rephrased as Is the multiple of the maximum $ K $ less than $ B $ more than $ A $ </ b>? Therefore, it is also possible to perform AC by determining whether this is satisfied by conditional branching. Since the amount of calculation is only judgment, it is $ O (1) $, but since the constraint is small, there is no need to do this.

The solution is easier to understand for Solution 1, so an example of the solution for Solution 1 is shown below.

Below are examples of answers for Python3, C ++, and Java.

Example of answer for each language

Example solution in Python3

{ABC165A.py}


K = int(input())
A,B = map(int,input().split())
flag = 0
#flag is the flag function(Whether there was a multiple of K)
for i in range(A,B+1):
#(A,B)Then A or more B-Be careful as you will check up to 1 or less! !!
  if i%K == 0:
    flag += 1
    print("OK")
    break
if flag == 0:
  print("NG")
Example solution in C ++

{ABC165A.cpp}


#include<bits/stdc++.h>
using namespace std;
int main(){
  int k,a,b;
  cin >> k;
  cin >> a >> b;
  int flag = 0;
  for (int i = a; i <= b; i++){
    if (i%k==0){
      flag++;
      cout << "OK" << endl;
      break;
    }
  }
  if (flag == 0){
    cout << "NG" << endl;
  }
}
Java answer example

{ABC165A.java}


import java.util.Scanner;
public class Main{
  public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    int k = scan.nextInt();
    int a = scan.nextInt();
    int b = scan.nextInt();
    int flag = 0;
    for (int i = a; i <=b; i++){
      if (i%k==0){
        flag++;
        System.out.println("OK");
        break;
      }
    }
    if (flag == 0){
      System.out.println("NG");
    }
  }
}

Recommended Posts