首页 > 代码库 > 复习篇 -- 递归和非递归方法实现N!
复习篇 -- 递归和非递归方法实现N!
import java.util.Scanner;
class Recursion{
public static void main(String argv[]){
System.out.println("chose the method to implement N! 1:recursion 2:not the recursion");
int n=0;
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
if(n==1){
System.out.println("input the n value: ");
n = scanner.nextInt();
System.out.println("the n! value are " + recursion(n));
}else if(n==2){
System.out.println("input the n value: ");
n = scanner.nextInt();
System.out.println("the n! value are " + noRecursion(n));
}
}
/*the recursion to implement the n!*/
public static long recursion(int n){
long res = 1;
if(n<=0){
res = 0;
return res;
}else if(n==1){
res = 1;
}else{
res = recursion(n-1)*n;
}
return res;
}
/*the simple method to implement the n!*/
public static long noRecursion(int n){
long res = 1;
if(n<=0){
res = 0;
return res;
}else if(n==1){
res = 1;
}else{
for(int i=1; i<=n; i++){
res *= i;
}
}
return res;
}
class Recursion{
public static void main(String argv[]){
System.out.println("chose the method to implement N! 1:recursion 2:not the recursion");
int n=0;
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
if(n==1){
System.out.println("input the n value: ");
n = scanner.nextInt();
System.out.println("the n! value are " + recursion(n));
}else if(n==2){
System.out.println("input the n value: ");
n = scanner.nextInt();
System.out.println("the n! value are " + noRecursion(n));
}
}
/*the recursion to implement the n!*/
public static long recursion(int n){
long res = 1;
if(n<=0){
res = 0;
return res;
}else if(n==1){
res = 1;
}else{
res = recursion(n-1)*n;
}
return res;
}
/*the simple method to implement the n!*/
public static long noRecursion(int n){
long res = 1;
if(n<=0){
res = 0;
return res;
}else if(n==1){
res = 1;
}else{
for(int i=1; i<=n; i++){
res *= i;
}
}
return res;
}
}
实验结果:
复习篇 -- 递归和非递归方法实现N!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。