洛谷1045-麦森数-C++-(快速幂+高精度乘法)

AC代码

#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
int ans[501]={0},bot[501]={0};
void init(){
	ans[0]=1;
	bot[0]=2;
}
void mult1(){
	int res[501]={0};
	for(int i=0;i<500;i++){
		for(int j=0;j<500-i;j++){
			res[i+j]+=ans[i]*bot[j];
			res[i+j+1]+=res[i+j]/10;
			res[i+j]%=10;
		}
	}
	memcpy(ans,res,sizeof(res));
}
void mult2(){
	int res[501]={0};
	for(int i=0;i<500;i++){
		for(int j=0;j<500-i;j++){
			res[i+j]+=bot[i]*bot[j];
			res[i+j+1]+=res[i+j]/10;
			res[i+j]%=10;
		}
	}
	memcpy(bot,res,sizeof(res));
}
void fast_power(int a,int b){
	init();
	while(b){
		if(b%2==1)
			mult1();
		mult2();
		b/=2;
	}
	ans[0]-=1;
}
int main(){
	int n;
	cin>>n;
	printf("%d\n",int(log10(2)*n)+1);
	fast_power(2,n);
	for(int i=499;i>=0;i--){
		printf("%d",ans[i]);
		if(i%50==0)
			printf("\n");
	}
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++中的高精度运算符重载是指对整数进行大数运算时,通过重载运算符来实现对大数的加减乘除等操作。一般情况下,C++内置的整数类型(如int、long等)有一定的位数限制,无法处理超过其表示范围的大数。而通过运算符重载,我们可以自定义一个类来表示大数,并对其进行各种运算操作。 以下是一个简单的示例,展示了如何实现C++中的高精度运算符重载: ```cpp #include <iostream> #include <vector> using namespace std; class BigInteger { private: vector<int> digits; // 用vector存储大数的每一位 public: BigInteger() {} BigInteger(int num) { while (num > 0) { digits.push_back(num % 10); num /= 10; } } BigInteger operator+(const BigInteger& other) const { BigInteger result; int carry = 0; int i = 0; while (i < digits.size() || i < other.digits.size() || carry != 0) { int sum = carry; if (i < digits.size()) { sum += digits[i]; } if (i < other.digits.size()) { sum += other.digits[i]; } result.digits.push_back(sum % 10); carry = sum / 10; i++; } return result; } friend ostream& operator<<(ostream& os, const BigInteger& num) { for (int i = num.digits.size() - 1; i >= 0; i--) { os << num.digits[i]; } return os; } }; int main() { BigInteger a(123456789); BigInteger b(987654321); BigInteger c = a + b; cout << "a + b = " << c << endl; return 0; } ``` 在上述示例中,我们定义了一个名为BigInteger的类,用于表示大数。通过重载加法运算符`+`,我们可以实现对两个BigInteger对象的相加操作。同时,我们还重载了输出流运算符`<<`,以便能够直接输出BigInteger对象的值。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值