Home >Java >javaTutorial >Practical small cases of java development basics

Practical small cases of java development basics

无忌哥哥
无忌哥哥Original
2018-07-23 09:51:451990browse

1. Recursive algorithm Find a certain number in the Fibonacci sequence

import java.util.Scanner;
public class diguisuanfa {
 public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int a=sc.nextInt();
    System.out.println(getNum(a));
}
 public static int getNum(int n ) {
     if(n<1) {
     System.out.println("输入不合法");
        return 0;
     }
     if(n==1|n==2) {
         return 1;
     }else {
        return getNum(n-2)+getNum(n-1);
     }    
 }
}

2. Sum the Fibonacci sequence

package CSDN;
import java.util.Scanner;
public class diguisuanfa {
    
     static int sum=0;
 public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int a=sc.nextInt();
    for(int i=1;i<=a;i++) {
        sum+=getNum(i);
    }
    System.out.println(sum);
}
 
 public static int getNum(int n ) {
     if(n<1) {
     System.out.println("输入不合法");
        return 0;
     }
     if(n==1|n==2) {
         return 1;
     }else {
        return getNum(n-2)+getNum(n-1);
     }
 }
}

3. Find the sum of 1~a certain number The sum of all integers between

//求1~某个数之间所有整数的和
public class qiuhe {
static int sum=0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
System.out.println(getNum(n));
}
public static int getNum(int n) {
if(n==1) {
return 1;
}else if(n>=1){
return n+getNum(n-1);
}else {
return getNum(n-1);
}
}
}

The above is the detailed content of Practical small cases of java development basics. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn