大众计算机学习网

专门提供各种电脑教程

计算min到max之间能被x或y整除的数的和

Admin | 2014-8-25 11:03:25 | 被阅次数 | 5439

  下面的代码功能是:计算min 到max 能被x或y整除的数的和。与其它代码相比,该代码是在C#环境下使用。

  /// <summary>
         /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public static int GetValue(int min, int max, int x, int y)
        {
            var result = 0;
            for (var i = min / x; i <= max / x; i++)
            {
                var temp = i * x;
                if (temp >= min && temp <= max)
                {
                    result += temp;
                }
            }
            for (var i = min / y; i <= max / y; i++)
            {
                var temp = i * y;
                if (temp >= min && temp <= max && temp % x != 0)
                {
                    result += temp;
                }
            }
            return result;
 
        }