跳到正文

题解

题解:P5703 【深基2.例5】苹果采购

Gilbert1206约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年5月10日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 1 分钟
获赞
3
题目
P5703

版本

  1. v1当前

题解:P5703 【深基2.例5】苹果采购

洛谷传送门

思路

这是一道简单的快速乘,非常的简单。快速乘的解法如下:

  1. 首先写出出口(注意 b=0b=0 的情况)
C++
if(b==0){
    return 0;
}
if(b==1){
    return a;
}
  1. 当 bb 为奇数时,我们把它变成偶数做。
C++
if(b%2==1){
    return a+tp(a,b-1);
}
  1. 当 bb 为偶数时,我们把它平均成两份。
C++
if(b%2==0){
    return tp(a,b>>1)+tp(a,b>>1);
}

Code

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long

int k;
int tp(int a,int b){
    if(b==0){
        return 0;
    }
	if(b==1){
		return a;
	}
	else{
		if(b%2==1){
			return a+tp(a,b-1);
		}
		else{
			return tp(a,b>>1)+tp(a,b>>1);
		}
	}
}
signed main(){
	int a,b;
	cin>>a>>b;
	cout<<tp(a,b);
    return 0;
}
原文
存档评论3 条抓取于