- 根据x*y=2(x*(y/2))当y为偶数时,这里的y/2为c语言中的整数除法,即向下取整
- 则当y为奇数时,x*y=2(x*(y/2))+x
- 所以x*y可以写成递归的形式,下面是程序的具体写法:
#include <iostream> #include <cstdio> using namespace std; int multiply(int x,int y); int main() { int x,y; int ans; cin>>x>>y; ans=multiply(x,y); cout<<ans<<endl; return 0; } int multiply(int x,int y) { if(y==0) { return 0; } int z=multiply(x,y/2); if(y%2==0) return 2*z; else return x+2*z; }
la Francais 算法
猜你喜欢
转载自blog.csdn.net/qq_34552393/article/details/79392189
今日推荐
周排行