zoukankan      html  css  js  c++  java
  • 递归_三角数字和阶乘

    递归是自己调用自己的编程技术,是程序设计中的数学归纳法。
    特征:调用自身;当调用自身的时候,是为了解决更小的问题;存在某个足够简单的问题的层次,在这一层算法中不需要调用自己就可以直接解答,且返回结果。
    当递归不再调用自己时就会退出递归。

    三角数字

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class Triangle {
        static int theNumber;//即数学中n的值
        public static void main(String[] args) throws IOException {
            System.out.print("输入 n 的值:");
            theNumber=getInt();
            int theAnswer=triangle(theNumber);
            System.out.print("三角数字是"+theAnswer);
    
        }
        
        private static int triangle(int n) {
            if(n==1)
                return 1;
            else
                return (n+triangle(n-1));
        }
    
        public static String getString() throws IOException {
            InputStreamReader inputStreamReader=new InputStreamReader(System.in);
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            return bufferedReader.readLine();
    
        }
        public static int  getInt() throws IOException {
            String string=getString();
            return Integer.parseInt(string);
        }
    
    }

    阶乘

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class Factorial {
        static int theNumber;//即数学中n的值
        public static void main(String[] args) throws IOException {
            System.out.print("输入 n 的值:");
            theNumber=getInt();
            int theAnswer=factorial(theNumber);
            System.out.print("阶乘是"+theAnswer);
    
        }
        
        private static int factorial(int n) {
            if(n==0)
                return 1;
            else
                return (n*factorial(n-1));
        }
    
        public static String getString() throws IOException {
            InputStreamReader inputStreamReader=new InputStreamReader(System.in);
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            return bufferedReader.readLine();
    
        }
        public static int  getInt() throws IOException {
            String string=getString();
            return Integer.parseInt(string);
        }
    
    }
  • 相关阅读:
    HDU 3951 (博弈) Coin Game
    HDU 3863 (博弈) No Gambling
    HDU 3544 (不平等博弈) Alice's Game
    POJ 3225 (线段树 区间更新) Help with Intervals
    POJ 2528 (线段树 离散化) Mayor's posters
    POJ 3468 (线段树 区间增减) A Simple Problem with Integers
    HDU 1698 (线段树 区间更新) Just a Hook
    POJ (线段树) Who Gets the Most Candies?
    POJ 2828 (线段树 单点更新) Buy Tickets
    HDU 2795 (线段树 单点更新) Billboard
  • 原文地址:https://www.cnblogs.com/S-Mustard/p/8097545.html
Copyright © 2011-2022 走看看