21天好习惯第一期—2

21天好习惯第一期—2

——算法竞赛中较为实用的C++库函数

1.__gcd(a,b);

作用:求a和b的最大公约数。

一般让我们去求两个数的公约数我们会采用辗转相除法。

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

殊不知还有更加简洁的方式去求的最大公约数,那就是采用C++的库函数 __gcd(a,b);

且看例题:

题解:求a和b的最小公倍数(两数相乘除以最大公约数)的结果再加一。

AC代码如下:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        long long a,b;
        cin>>a>>b;
        cout<<a*b/__gcd(a,b)+1<<endl;
    }
}

2.bitset<n> b(m);

作用:可实现十进制和二进制的互换,参数n表示结果为n位数,参数m为要实现装换的数。

#include <bits/stdc++.h> 
using namespace std;
int main( )
{
    bitset<8> b1 ( 4 );
    cout << "The set of bits in bitset<8> b1( 4 ) is: ( "
        << b1 << " )." << endl;
    bitset<8> b2 ( 6 );
    cout << "The set of bits in bitset<8> b2( 6 ) is: ( "
        << b2 << " )." << endl;
}
//输出:The set of bits in bitset<8> b1( 4 ) is: ( 00000100 ).
      //The set of bits in bitset<8> b2( 6 ) is: ( 00000110 ). 

3.lower_bound (begin ,end ,val)

作用:查找有序区间[begin,end]中第一个大于等于val的位置

4.sort(begin, end,cmp)

作用:给一个k[n]数组,sort(k+0,k+n);这是对k数组的第一个到第n-1个元素进行升序,第三个参数cmp默认为升序。

#include <bits/stdc++.h>
using namespace std;
const int N=9;
int main()
{  
  int a[N] = {9,8,7,6,5,4,3,2,1} ; 
  sort(a+0,a+N);
  for(int i=0;i<N;i++)
  cout<<a[i]<<" "; 
  return 0;
}
//输出:1 2 3 4 5 6 7 8 9 

5.copy(begin,end,begin)
作用:将第一个数组的begin至end 赋值到第二个容器begin开始。

#include <bits/stdc++.h>
using namespace std;
const int N=9;
int main()
{  
  int a[N] = {1,2,3,4,5,6,7,8,9} ;
  int b[N] = {9,8,7,6,5,4,3,2,1} ; 
  copy(a,a+5,b); 
  for(int i=0;i<N;i++)
  cout<<b[i]<<" "; 
  return 0;
}
//输出:1 2 3 4 5 4 3 2 1 

6. minmax ,swap函数

作用:min(a , b):求a和b的最小值,max(a , b):求a和b的最大值,swap(a , b):交换a和b的值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值