| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 715 人关注过本帖
标题: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
快速回复:pow(a, b): can we do it iteratively using lgn multiplications?
数据加载中...
 
   



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

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