zoukankan      html  css  js  c++  java
  • 取一个任意数所有 和的等式

    前几天,同学给出了一个算法题

     随便输入一个数,输出 相加等于这个数的所有等式,而且加数不能重复

      例如:6

      6=1+5;

      6=2+4;

      6=1+2+3;

      --------------------------------

      程序如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace _111301
    {
        class Program
        {
            static int total = 0;
            static void Main(string[] args)
            {
                Console.WriteLine("请输入数字:");
                int Num = 0;
                Num =Convert.ToInt32(Console.ReadLine().ToString());
                Console.WriteLine("-----------------等式如下:-------------------");
                for (int i = 1; i < (Num % 2 == 0 ? Num / 2 : Num / 2 + 1);i++ )
                {
                    PrintNum(Num.ToString() + "=" + i.ToString(), i, i, Num);
                }
                Console.WriteLine("------------共计:"+total.ToString()+"个-------------------------");
                Console.ReadKey();
            }
            /// <summary>
            /// 打印数字
            /// </summary>
            /// <param name="preInfo">此数字前面数字</param>
            ///  /// <param name="preInfo">此前数字和</param>
            /// <param name="flagNum">当前标志数字</param>
            /// <param name="maxNum">输入数字</param>
            private static void PrintNum(string preInfo,int preTotal,int flagNum,int maxNum)
            {
                Console.WriteLine(preInfo + "+" + (maxNum - preTotal).ToString());
                total++;
                for (int i = flagNum + 1; i <= (maxNum - preTotal - 1) / 2; i++)
                {
                    string tempPreInfo = preInfo;
                    int tempPreTotal = preTotal;
                    tempPreTotal += i;
                    tempPreInfo += "+" + i.ToString();
                    if (i<=maxNum-preTotal-1)
                    {
                        PrintNum(tempPreInfo, tempPreTotal, i, maxNum);
                    }else{
                        continue;
                    }
                }

            }
        }
    }

    ---------------------------------------------------------------------------

  • 相关阅读:
    yum工具及Linux中jdk,tomcat安装
    SSH工作机制和网络配置
    Linux目录,权限,用户管理的命令
    安装Linux服务及其网络配置
    使用Jedis,JedisPool,JedisCluster链接redis
    springboot项目整合定时任务
    pageHelper分页原理及实战
    Net异步委托-泛型委托Action<T>与Func<T,TResult>及 异步调用AsyncCallback
    Oracle 数据库操作相关脚本
    运行npm报错:无法加载文件 D: odejs ode_globalwebpack.ps1,因为在此系统上禁止运行脚本
  • 原文地址:https://www.cnblogs.com/xianzuoqiaoqi/p/1605315.html
Copyright © 2011-2022 走看看