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
(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'
.
・ All inputs are integers ・ $ 1 \ leq A \ leq B \ leq 1000 $ ・ $ 1 \ leq K \ leq 1000 $
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) $.
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.
{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")
{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;
}
}
{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