标题:pow(a, b): can we do it iteratively using lgn multiplications?
只看楼主
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
 问题点数:0 回复次数:4 
pow(a, b): can we do it iteratively using lgn multiplications?

/*---------------------------------------------------------------------------
File name: pow.c
Author: HJin (email: fish_sea_bird [at] yahoo [dot] com )
Created on: 7/22/2007 17:47:04
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762


Modification history:
===========================================================================

Post: pow(a, b): can we do it iteratively using lgn multiplications?

Following code calculates a^b using lgn multiplications. But it is recursive.

Question:

Can we do it using a loop?


Don't use a stack to convert recursion into iteration, 'coz that does not solve
the problem.
*/


#include <stdio.h>

/**
Calculates a^b using lgn multiplications.
*/
int pow(int a, int n)
{
int t;

if(n==0)
return 1;

t=pow(a, n/2);
t*=t;
if(n&1)
t*=a;

return t;
}

int main()
{
int a=3, i;

for(i=0; i<21; ++i)
printf("%d\n", pow(a, i));

return 0;
}

搜索更多相关主题的帖子: pow using iteratively lgn 
2007-07-23 09:08
leeco
Rank: 4
等 级:贵宾
威 望:10
帖 子:1026
专家分:177
注 册:2007-5-10
得分:0 

对于a^b,可以将b视作若干2的幂的和的形式,例如2^10可以视作2^(2+8)=2^2*2^8,这样就表示成了若干 (a的(2的幂)的幂)的乘积 的形式,我用一个变量y循环得到a^2,a^4,a^8,...,用对b的位运算判断结果t是否应该有当前的y作为因子,如果有就乘上去


#include <stdio.h>
#include <stdlib.h>
int power(int a,int b)
{
int t=1,y=a;
while(b){
if(b&1)
t*=y;
y=y*y;
b>>=1;
}
return t;
}

int main()
{
printf(\"%d\n\",power(2,10));
printf(\"%d\n\",power(10,3));
printf(\"%d\n\",power(1,100));
printf(\"%d\n\",power(100,0));
//system(\"pause\");
}


2007-07-23 10:50
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
得分:0 
thanks, that is a neat solution.

I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-07-23 11:35
aipb2007
Rank: 8Rank: 8
来 自:CQU
等 级:贵宾
威 望:40
帖 子:2879
专家分:7
注 册:2007-3-18
得分:0 
学习了,递归解和迭代解都很厉害!

Fight  to win  or  die...
2007-07-23 14:32
stupid_boy
Rank: 1
等 级:新手上路
帖 子:53
专家分:0
注 册:2007-7-6
得分:0 

有收获!!!


失眠。。。
2007-07-23 15:08



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-157370-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.230336 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved