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

既然选择了python,就要承担超时的风险,过了三个点

#快速幂算法+高精度乘法
import math
ans=[0]*501
bot=[0]*501
ans[0]=1
bot[0]=2

#计算位数
def count(n):
    return int(math.log10(2)*n)+1

#快速幂算法
def fast_pow(a,b):
    ans=1
    while b:
        if b%2==1:
            mult1()
        mult2()
        b=b//2

#对于高精度乘法 只在乎后500位
#高精度乘法 equal to ans*=a
def mult1():
    global ans
    global bot
    res=[0]*501
    for i in range(500):
        for j in range(500-i):
            res[i+j]+=ans[i]*bot[j]
            res[i+j+1]+=res[i+j]//10
            res[i+j]=res[i+j]%10
    ans=res.copy()

#equal to a*=a
def mult2():
    global bot
    res=[0]*501
    for i in range(500):
        for j in range(500-i):
            res[i+j]+=bot[i]*bot[j]
            res[i+j+1]+=res[i+j]//10
            res[i+j]=res[i+j]%10
    bot=res.copy()
if __name__=="__main__":
    n=int(input())
    print(count(n))

    fast_pow(2,n)
    ans[0]-=1
    for i in range(499,-1,-1):
        print(ans[i],end="")
        if i%50==0:
            print()

洛谷示例
在这里插入图片描述
编译器结果
在这里插入图片描述
尝试用C++重构,直接过了
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值