牛客网———整数拆分

本文介绍了一种计算整数拆分为2的幂之和的不同方式数量的算法,并提供了一个C++实现示例。该算法使用动态规划方法,适用于输入整数不超过1000000的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

一个整数总可以拆分为2的幂的和,例如: 7=1+2+4 7=1+2+2+2 7=1+1+1+4 7=1+1+1+2+2 7=1+1+1+1+1+2 7=1+1+1+1+1+1+1 总共有六种不同的拆分方式。 再比如:4可以拆分成:4 = 4,4 = 1 + 1 + 1 + 1,4 = 2 + 2,4=1+1+2。 用f(n)表示n的不同拆分的种数,例如f(7)=6. 要求编写程序,读入n(不超过1000000),输出f(n)%1000000000。
链接:https://www.nowcoder.com/questionTerminal/376537f4609a49d296901db5139639ec
来源:牛客网

#include<iostream>
#define MAXSIZE 1000001
using namespace std;
 
int main(){
    int n;
    int result[MAXSIZE];
    result[0] = result[1] = 1;
    for(int i = 2; i<MAXSIZE; ++i){
        if(i%2 == 0){
            result[i] = (result[i-1] + result[i/2])%1000000000;
        }
        else{
            result[i] = result[i-1]%1000000000;
        }
    }
    while(scanf("%d",&n) != EOF)
        cout<<result[n]<<endl;
    return 0;
}

  

转载于:https://www.cnblogs.com/JAYPARK/p/10055647.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值