您的位置:首页 > 编程语言 > Java开发

X的N次方 朴素分治法-Java

2016-05-25 17:42 316 查看
http://open.163.com/special/opencourse/algorithms.html

算法导论里讲了

计算x的N次方计算方法,

很节省资源的一种算法。

II.朴素算法 x的n次方

x相乘N次

朴素算法的分治法

n是偶数

计算x 的n/2次方 然后两个相乘

n是奇数

计算x的(n-1)/2次方 两个相乘 再乘以x

留个备份不知道啥时候能用到

package com.ding.acm;
/**
* 效率比x*x*x*x*x高
* @author daniel
* @email 576699909@qq.com
* @time 2016-5-25 下午5:36:13
*/
public class XtoN {

/**
* @author daniel
* @time 2016-5-25 下午5:29:59
* @param args
*/
public static void main(String[] args) {

System.out.println(cube(2,4));
}
/**
* x的n次方计算
* @author daniel
* @time 2016-5-25 下午5:35:33
* @param x
* @param n
* @return
*/
public static int cube(int x, int n) {
int returnData = -1;
if (n == 1) {
returnData = x;
} else if (n > 1) {

int m = n / 2;
int s = cube(x, m);
if (n % 2 == 0) {
returnData = s * s;
} else {
returnData = x * s * s;
}

}

return returnData;
}

}


源码:

https://github.com/dingsai88/StudyTest/tree/master/src/com/ding/acm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: