Home > Java > Java Tutorial > body text

Practical small cases of java development basics

无忌哥哥
Release: 2018-07-23 09:51:45
Original
1819 people have browsed it

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);
     }    
 }
}
Copy after login

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);
     }
 }
}
Copy after login

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);
}
}
}
Copy after login

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!

source:php.cn
Statement of this Website
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!