C++小代码

本文介绍了如何用C++实现欧几里得法求最大公约数、递归求斐波那契数列和阶乘,以及简单DFS进行全排列和二分查找算法的应用。
摘要由CSDN通过智能技术生成

//新生训练

//欧几里得法求最大公约数

#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    int a,b;
    cin>>a>>b;
    int r = a%b;
    while (r!=0){
        a = b;
        b = r;
        r = a%b;
    }
    cout<<b<<endl;
    return 0 ;
}

//递归法求斐波那契数列

#include <iostream>
#include <algorithm>
using namespace std;
int Fib(int x)
{
	if (x == 1)
	{
		return 0;
	}
		
	else if (x == 2)
	{
		return 1;
	}	
	else
	{
		return Fib(x - 1) + Fib(x - 2);
	}	
}
int main()
{
	int n = 0;
	cin >> n;//第n个斐波那契数
	cout << Fib(n);
	return 0;
}

//递归求阶乘

#include <bits/stdc++.h>
using namespace std;
int f(int n) {
	if(n==1) return 1;
	else{
		return n*f(n-1);
	}
}
int main() {
	int n = 0;
	cin >> n;
	int sum = f(n);
	cout << sum;
	return 0;
}

//简单DFS(全排列)

#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
int a[10], b[10];
int n;
void dfs(int u)// u表示深度,当前选的是第几个数字
{ 
    if (u > n)// 最后一个数字已经选完,输出答案
    { 
        for (int i = 1; i <= n; i++)
        {
            cout << a[i] << ' ';
        }
        cout << endl;
        return; // 回到上一个数字,重新选上一个数字
    }
    for (int i = 1; i <= n; i++)
    {
        if (!b[i])
            continue; // 如果数字i已经选了就跳过
        b[i] = 1;     // 数字i没选过,选择数字i,标记已选择数字i
        a[u] = i;     // 将数字i填入第u个位置
        dfs(u + 1);   // 选择下一个(第u+1个)数字
        b[i] = 0;     // 重新选择第u个数字为i+1,标记数字i未选择
    }
}
int main()
{
    cin >> n;
    dfs(1);
    return 0;
}

//简单二分查找(某个数是否在某个数组中)

#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int main()
{
    long long a[N];
    long long n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    sort(a, a + n);
    while (m--)
    {
        long long k;
        cin >> k;
        long long l = 0;
        long long r = n - 1;
        while (l <= r)
        {
            long long mid = (l + r) / 2;
            if (a[mid] < k)
            {
                l = mid + 1;
            }
            else if (a[mid] > k)
            {
                r = mid - 1;
            }
            else
            {
                cout << "YES" << endl;
                break;
            }
        }
        if (l > r)
        {
            cout << "NO" << endl;
        }
    }
    return 0;
}

//笔者暂时想出这些,想到了之后再补;

~~~//仅当笔者个人备忘录使用。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值