CSP常用算法

判断闰年

bool leap_year(int year){
	//非整百年的,能被4整除
	if(year % 100 != 0){
    	if(year % 4 == 0){
    		return true;
    	}
	}else{//非整百年的,能被400整除
		if(year % 400 == 0){
    		return true;
    	}
	}
	return false;	
}

最大公约数

int gcd(int a, int b){
	int c = 1;
	while(c > 0){
		c = a % b;
		a = b;
		b = c;
	}
	return a;
}

判断素数

bool isprime(int a){
	int sqrt_a = sqrt(a);
	for(int i = 2; i <= sqrt_a; i++){
		if(a % i == 0){
			return false;
		}
	}
	return true;
}

筛法求素数

const int n = 100;
int x[n];
int prime[n];
int prime_list() {
	int count = 1;
	x[0] = x[1] = 1;
	for(int i = 2; i <= n; i++) {
		if(x[i] == 0) {
			prime[count] = i;
			++count;
		}
		for(int j = 1; j < count && prime[j] * i < n; ++j)
			x[prime[j] * i] = 1;
	}
	return count;
}

十进制转X进制

#include <iostream>
#include <cstdio>
using namespace std;
string dict = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//十进制转 x 进制函数。
string ten_to_x(int n, int x){
	string ans = "";
	//模拟短除法。 
	while (n != 0) {
		ans += dict[n % x];
		n /= x;
	}
	string t = "";  //倒取余数。
	for (int i = ans.length()-1; i >= 0; i--) t += ans[i];
	return t; 
}
int main(){
	int n, x;
	cin >> n >> x;
	cout << ten_to_x(n, x);
	return 0;
}

X进制转10进制

#include <bits/stdc++.h>
using namespace std;

// char转数码
int charToInt(char c) {
    if('0' <=c && c<='9') return c-'0';
    return c-'A' + 10;
}

int x_to_ten(int x, string s){
	int a[105];
    int len = s.size();
    for(int i = len - 1; i >= 0; i--)
        a[len - 1 - i] = charToInt(S[i]);
    int ans = 0, w = 1;
    for(int i = 0; i < len + 1; i++){
        ans = ans + w * a[i];
        w = w * x;
    }
    return ans;
}

int main(void) {
	int x; // 输入x进制
	string s;
    cin >> x >> s;
    cout << x_to_ten(x, s);
    return 0;
}

表达式计算

#include<iostream>
#include<algorithm>
#include<string>
#include<stack>
using namespace std;
string str;
 
long long calculate(string str)
{
	int len=str.length(),pos=0;
	stack<long long> sta;
	char ch;
	
	while(pos < len){
		if(str[pos] >='0' && str[pos] <= '9'){
			long long temp=0;
			while(str[pos]!=' '&&str[pos]!='.') temp=temp*10+(str[pos++]-'0');
			sta.push(temp);
		}else if(str[pos]==' '||str[pos]=='.') {
			pos++;
		}else if(str[pos]=='@'){
		 	break;
		}else{
			ch=str[pos++];
			int num1,num2;
			num2=sta.top(); sta.pop();
			num1=sta.top(); sta.pop();
			
			switch(ch){
				case '+': sta.push(num1+num2); break;
				case '-': sta.push(num1-num2); break;
				case '*': sta.push(num1*num2); break;
				case '/': sta.push(num1/num2); break;
			}
		}
	}
	return sta.top();
}
 
int main(){
	getline(cin,str);
	cout << calculate(str);
	return 0;
}
  • 2
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值