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



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




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

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