zoukankan      html  css  js  c++  java
  • hdu2669 6thweek trainning problem I、数论、线性方程

    Description

    The Sky is Sprite.  The Birds is Fly in the Sky.  The Wind is Wonderful.  Blew Throw the Trees  Trees are Shaking, Leaves are Falling.  Lovers Walk passing, and so are You.  ................................Write in English class by yifenfei 

    Girls are clever and bright. In HDU every girl like math. Every girl like to solve math problem!  Now tell you two nonnegative integer a and b. Find the nonnegative integer X and integer Y to satisfy X*a + Y*b = 1. If no such answer print "sorry" instead. 
     

    Input

    The input contains multiple test cases.  Each case two nonnegative integer a,b (0<a, b<=2^31) 
     

    Output

    output nonnegative integer X and integer Y, if there are more answers than the X smaller one will be choosed. If no answer put "sorry" instead. 
     

    Sample Input

    77 51
    10 44
    34 79
     

    Sample Output

    2 -3
    sorry
    7 -3
     
    题意:
    给你a和b,叫你求ax+by=1的x和y,要求是x为正整数,y为整数...   有就输出,没有就输出sorry。
     
    分析:
    扩展欧几里德算法。先用扩展欧几里德算法求出x,y然后再判断x是否大于0,如果小于0,则通过循环+b,直到x>0,在输出答案
     
     代码:
     1 #include<iostream>
     2 #include<cstdio>
     3 using namespace std;
     4 
     5 long long exgcd(long long a,long long b,long long& x,long long& y)
     6 {
     7     if(b==0)
     8     {
     9         x=1,y=0;
    10         return a;
    11     }
    12     long long g = exgcd(b,a%b,y,x);
    13     y -= a/b*x;
    14     return g;
    15 }
    16 
    17 int main()
    18 {
    19     long long m,n,x1,y1;
    20     while(cin >> m >> n)
    21     {
    22         if (exgcd(m,n,x1,y1) != 1)
    23             printf("sorry
    ");
    24         else
    25         {
    26             while(x1< 0)
    27             {
    28                  x1+= n;
    29                  y1-= m;
    30             }
    31             printf("%I64d %I64d
    ",x1,y1);
    32         }
    33     }
    34     return 0;
    35 }
    View Code
  • 相关阅读:
    (C/C++学习笔记) 五. 常变量(只读变量)和宏
    (C/C++学习笔记) 四. 运算符
    (C/C++学习笔记) 三. 作用域和可见性
    (C/C++学习笔记) 一. 基础知识
    计算机科学的基本术语及其英语表达
    模块与包
    Python的递归
    内置函数与匿名函数
    装饰器,迭代器,生成器分析
    命名关键字参数,函数对象,嵌套,名称空间与作用域,闭包
  • 原文地址:https://www.cnblogs.com/x512149882/p/4750788.html
Copyright © 2011-2022 走看看