数学基础问题汇总

1、素数的判断:

#include<bits/stdc++.h>
typedef long long LL;
const int MaxN = 1e5;
using namespace std;

int a[MaxN + 5],n;
int is_Prime(int x)
{
	if(x==1 || x==2) return 0;
	for(int i=2; i*i<=x; ++i)
		if(x%i == 0)return 0;
	return 1;
}
int main(){
    while(cin>>n){
		if(is_Prime(n))
			cout<<n<<" is Prime"<<endl;
		else cout<<n<<" not is Prime"<<endl;
    }
    return 0;
}

2、最大公约数和最小公倍数:

#include<bits/stdc++.h>
typedef long long LL;
const int MaxN = 1e5;
using namespace std;

int a[MaxN + 5],m,n;
int main(){
    while(cin>>n>>m){
    	int x = __gcd(m,n);  //最大公约数
    	int y = m * n / x;   //最小公倍数
    	printf("%d 和 %d 的最大公约数是 %d\n",m,n,x);
    	printf("%d 和 %d 的最小公倍数是 %d\n",m,n,y);
    }
    return 0;
}

3、任意进制之间的转换:

#include<bits/stdc++.h>
typedef long long LL;
const int MaxN = 1e5;
using namespace std;

int a[MaxN + 5],m,n;//将十进制数 m 转换为 n 进制数
stack<int>s;
int main(){
    while(cin>>m>>n){
    	int k = 0;
    	while(m>0){
			int e = m%n;
			s.push(e);
			m /= n;
    	}
    	while(!s.empty()){
			cout<<s.top();
			s.pop();
    	}
    	cout<<endl;
    }
    return 0;
}

4、atoi()函数的实现

atoi()函数的功能:将字符串转化为整型数

输出上界或下界:-2147483648~2147483647

#include<bits/stdc++.h>
typedef long long LL;
const int MaxN = 1e5;
using namespace std;

int a[MaxN + 5],m,n;
char s1[10],s2[10];
int main(){
    while(cin>>s1>>s2){
		LL x = atoi(s1);
		LL y = atoi(s2);
		cout<<x<<endl<<y<<endl;
    }
    return 0;
}

5、判断一个数是否为完全平方数:

#include<bits/stdc++.h>
typedef long long LL;
const int MaxN = 1e5;
using namespace std;

int a[MaxN + 5],m,n;
int main(){
    while(cin>>n){
    	if(sqrt(n) == (int) sqrt(n))  //sqrt(x) == (int) sqrt(n) ? YES:NO;
    		cout<<n<<" is a Perfect Squares"<<endl;
    	else
    		cout<<n<<" not is a Perfect Squares"<<endl;
    }
    return 0;
}

6、判断一个数是否是2的幂次方

将2的幂次方写成二进制形式后,很容易就会发现有一个特点:二进制中只有一个1,并且1后面跟了n个0。如果将这个数减去1后会发现,仅有的那个1会变为0,而原来的那n个0会变为1;因此将原来的数与减去1后的数字进行与运算后会发现为零。

例如:2(10)、4(100)、8(1000)、16(10000)……

(n & n-1) == 0



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值