zoukankan      html  css  js  c++  java
  • CodeChef GCD2

    GCD2

     
    Problem code: GCD2
     

    All submissions for this problem are available.

    Frank explained its friend Felman the algorithm of Euclides to calculate the GCD
    of two numbers. Then Felman implements it algorithm

    int gcd(int a, int b)
    {
    	if (b==0)
    		return a;
    	else
    		return gcd(b,a%b);
    }
    

    and it proposes to Frank that makes it
    but with a little integer and another integer that has up to 250 digits.

    Your task is to help Frank programming an efficient code for the challenge of Felman.

    Input

    The first line of the input file contains a number representing the number of lines to follow.
    Each line consists of two number A and B (0 <= A <= 40000 and A <= B < 10^250).

    Output

    Print for each pair (A,B) in the input one integer representing the GCD of A and B.

    Example

    Input:
    2
    2 6
    10 11
    
    
    Output:
    2
    1
    
    

    求一个大数 , 一个<=4W整数的GCD 。。

    枚举整数的约数, 模拟大数除法 ,用大数除去这些约数,判一下余数是否为0

    #include <bits/stdc++.h>
    
    using namespace std;
    const int N = 100010;
    int A,BB[N],num[N],tot;
    char s[300];
    vector<int>B;
    inline int gcd( int a , int b ) { return b == 0 ? a : gcd(b,a%b); }
    
    bool check( int n ) {
        int c = 0 ;
        for( int i = 0 ; i < B.size() ; ++i ) {
            c = c * 10 + B[i];
            c %= n ;
        }
        if( c == 0 ) return true ;
        return false;
    }
    
    void Run() {
        scanf("%d %s",&A,s);
        tot = 0;
        int n = strlen(s) ;
        if( A == 1 ) { puts("1"); return ; }
        else if( A == 0 ) { puts(s); return ; }
        B.resize(n);
        for( int i = 0 ; i < strlen(s) ; ++i ) B[i] = s[i] - '0';
        for( int i = 1 ; i <= A ; ++i ) if( A % i == 0 ) {
            num[tot++] = i ;
        }
        for( int i = tot-1 ; i >= 0 ; --i ) if( check(num[i]) ) {
            printf("%d
    ",num[i]);
            return ;
        }
    }
    int main()
    {
        //freopen("in","r",stdin);
        int _ , cas = 1 ;
        scanf("%d",&_);
        while(_--)Run();
    }
    View Code
  • 相关阅读:
    LintCode "Maximum Gap"
    LintCode "Wood Cut"
    LintCode "Expression Evaluation"
    LintCode "Find Peak Element II"
    LintCode "Remove Node in Binary Search Tree"
    LintCode "Delete Digits"
    LintCode "Binary Representation"
    LeetCode "Game of Life"
    LintCode "Coins in a Line"
    LintCode "Word Break"
  • 原文地址:https://www.cnblogs.com/hlmark/p/4296952.html
Copyright © 2011-2022 走看看