using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ExchangeDemo { class Program { static void Main(string[] args) { int number1, number2; Console.WriteLine("求用1,2,5这三个数不同个数组合的和为100的组合个数"); number1 = SimpleSolution(); Console.WriteLine("算法一组合数:" + number1 + ""); number2 = Optimize(); Console.WriteLine("算法二组合数:" + number2 + " "); int nu1 = 0; int nu2 = 0; int nu5 = 0; int count = 0; for (nu5 = 0; nu5 < 21; nu5++) { for (nu2 = 0; nu2 < 51; nu2++) { for (nu1 = 0; nu1 < 101; nu1++) { if (nu1 + nu2*2 + nu5*5 == 100) { if (nu1 != 0) { Console.Write("" + nu1 + "*1"); } if (nu2 != 0 && nu5 != 0) { Console.Write("+" + nu2 + "*2+" + nu5 + "*5"); } else if (nu2 != 0 && nu5 == 0) { Console.Write("+" + nu2 + "*2"); } else if (nu2 == 0 && nu5 != 0) { Console.Write("+" + nu5 + "*5"); } Console.WriteLine("=100 "); count++; } } } } Console.WriteLine("总的组合数为" + count + ""); Console.Read(); } public static int SimpleSolution() { int number=0; for(int i=0;i<=100;i++) for(int j=0;j<=50;j++) for(int k=0;k<=20;k++) { if(i+2*j+5*k==100) number++; } return number; } public static int Optimize() { //组合总数为100以内的偶数+95以内的奇数+90以内的偶数+...+5以内的奇数+1 int number = 0; for (int m = 0; m <= 100; m += 5) { number += (m + 2) / 2; // 某个偶数m以内的偶数个数(包括0)可以表示为m/2+1=(m+2)/2 //某个奇数m以内的奇数个数也可以表示为(m+2)/2 } return number; } } }