<OJ_Sicily>Greatest Common Divisors

来源:互联网 发布:java注释的作用 编辑:程序博客网 时间:2024/05/17 06:06

Description

A common divisor for two positive numbers is a number which both numbers are divisible by. It's easy to calculate the greatest common divisor between tow numbers. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low<=d<=high. It is possible that there is no common divisor in the given range.

Input

The first line contains an integer T (1<=T<=10)- indicating the number of test cases.

For each case, there are four integers a, b, low, high (1<=a,b<=1000,1<=low<=high<=1000) in one line.

题目解释:求解两个数a和b在范围low和high之间的最大公约数。实质就是求a和b的公约数,然后符合该公约数在范围low和high之间是最大的

解题思路:使用一个for循环,从a和b中取较小的数,假如较小数是b,从b开始逐渐减一求得符合要求的值

#include <iostream>using namespace std;int main(int argc, const char * argv[]) {    // insert code here...    int T, a, b, low, high;    cin >> T;    while (T > 0) {        cin >> a >> b >> low >> high;        int tmp = 0;        if (a < b) {            tmp = a;            a = b;            b = tmp;        }        bool has_answer = false;        int result = 0;        for (int i = b; i >= 1 ; i--) {   // 从小的数开始,逐个找到符合要求的值            if ((b % i) == 0 && (a % i) == 0 && i >= low && i <= high) {                has_answer = true;                result = i;                break;            }        }        if (has_answer) cout << result<< endl;        else cout << "No answer" << endl;        T--;    }    return 0;}


0 0
原创粉丝点击