[HDU] [2504] GCD Again

Problem Description

Loading...

Problem Analysis

Brute-force search works
but it can be optimized based on the problem statement
c must be a multiple of b
so each step can use i+=b
and since c != b
the initial condition can start from i=b+b

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include<stdio.h>
int gcd(int a,int b) {
    if(b==0)
        return a;
    return gcd(b,a%b);
}
int main() {
    int T;
    scanf("%d",&T);
    while(T--) {
        int a,b;
        scanf("%d %d",&a,&b);
        for(int i=b+b; i<1000000; i+=b)
            if(gcd(a,i)==b) {
                printf("%d\n",i);
                break;
            }
    }
    return 0;
}

Loading...