zoukankan      html  css  js  c++  java
  • 从1加到N的简单实现

    一直搞web应用层程序开发,基本算法依然忘记干净。

    这不一次去某公司面试,让我用递归写个从1加到N的方法,一时间卡壳,竟然丢份了。

    回来后,在电脑上把方法一写,居然发现如此简单,唉!为了给自己以后警钟,就把这实现记录在此!

    package cn.com.szgr.method;

    public class ArithMetic {

       /**
        * 数学公式实现指定步长step从m加到n
        *
        * @param start
        * @param end
        * @param step
        * @return
        */
        public int Math(int start, int end, int step) {
            return ((end * (end - step) / 2) - (start * (start - step) / 2)) + end;
        }

       /**
        * 递归算法实现指定步长step从m加到n
        *
        * @param start
        * @param end
        * @param step
        * @return
        */
        public int Recursion(int start, int end, int step) {
            int count = start;
            if (start < end) {
                count += Recursion(start + step, end, step);
           }
           return count;
        }

        /**
         * 用循环实现指定步长step从m加到n
        *
        * @param start
        * @param end
        * @param step
        * @return
        */
        public int Repeat(int start, int end, int step) {
            int count = 0;
            for (int i = start; i <= end; i += step) {
                count += i;
           }
            return count;
        }

        public static void main(String[] args) {
            ArithMetic arithMetic = new ArithMetic();
            System.out.println(arithMetic.Recursion(1, 10, 1));
            System.out.println(arithMetic.Repeat(1, 10, 1));
            System.out.println(arithMetic.Math(1, 10, 1));
       }
    }

    程序输出结果为:

    55

    55

    55

  • 相关阅读:
    How to alter department in PMS system
    Can't create new folder in windows7
    calculate fraction by oracle
    Long Wei information technology development Limited by Share Ltd interview summary.
    ORACLE BACKUP AND RECOVERY
    DESCRIBE:When you mouse click right-side is open an application and click left-side is attribution.
    ORACLE_TO_CHAR Function
    电脑BOIS设置
    JSP点击表头排序
    jsp+js实现可排序表格
  • 原文地址:https://www.cnblogs.com/aDust/p/Recursion.html
Copyright © 2011-2022 走看看