java: 用递归和非递归两种写出N!写1+1/2-1/3+1/4-1/5……+1/n程序
推荐于2018-04-11
展开全部
public class Digui {
//递归算法:
public static double digui(int n){
double sum = 0.0;
if (n == 1) {
sum = 1;
}else{
if (n%2 == 0) {
sum = 1.0/n+digui(n-1);
}else{
sum = -1.0/n+digui(n-1);
}
}
return sum;
}
//非递归算法:
public static double feidigui(int n){
double count = 0.0;
StringBuffer sb = new StringBuffer();
for (double i = 1; i <= n; i++) {
if (i == 1) {
count = 1;
sb.append("n!="+n+"!=1");
}else{
if (i%2 == 0) {
count = count+1/i;
sb.append("+1/"+(int)i);
}else{
count = count-1/i;
sb.append("-1/"+(int)i);
}
}
}
System.err.println(sb.toString());
return count;
}
public static void main(String[] args) {
int n = 10;
double digui = feidigui(n);
double feidigui = digui(n);
System.out.println("递归算法:"+n+"! = "+digui);
System.out.println("非递归算法:"+n+"! = "+feidigui);
}
}
运行结果如下:
n!=10!=1+1/2-1/3+1/4-1/5+1/6-1/7+1/8-1/9+1/10
递归算法:10! = 1.3543650793650797
非递归算法:10! = 1.3543650793650797
//递归算法:
public static double digui(int n){
double sum = 0.0;
if (n == 1) {
sum = 1;
}else{
if (n%2 == 0) {
sum = 1.0/n+digui(n-1);
}else{
sum = -1.0/n+digui(n-1);
}
}
return sum;
}
//非递归算法:
public static double feidigui(int n){
double count = 0.0;
StringBuffer sb = new StringBuffer();
for (double i = 1; i <= n; i++) {
if (i == 1) {
count = 1;
sb.append("n!="+n+"!=1");
}else{
if (i%2 == 0) {
count = count+1/i;
sb.append("+1/"+(int)i);
}else{
count = count-1/i;
sb.append("-1/"+(int)i);
}
}
}
System.err.println(sb.toString());
return count;
}
public static void main(String[] args) {
int n = 10;
double digui = feidigui(n);
double feidigui = digui(n);
System.out.println("递归算法:"+n+"! = "+digui);
System.out.println("非递归算法:"+n+"! = "+feidigui);
}
}
运行结果如下:
n!=10!=1+1/2-1/3+1/4-1/5+1/6-1/7+1/8-1/9+1/10
递归算法:10! = 1.3543650793650797
非递归算法:10! = 1.3543650793650797
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询