求出10000以下符合條件的自然數。條件是:千位數字與百位數字之和等于十位數字與個位數字之和,且千位數字與百位數字之和等于個位數字與千位數字之差的10倍。計算并輸出這些四位自然數的個數cn以及這些數的和sum。
uj5u.com熱心網友回復:
假設四位數是abcd,由條件有a+b=c+d,a+b=10*(d-a),可以得到c和d關于a,b的運算式,10*d=11*a+b,c=a+b-d,注意到0<=d<=9,0<=c<=9且c,d都是整數,因此兩個回圈就可以解決問題了。int a,b,c,d;
List<int> result = new List<int>();
for(a=1;a<=9;a++)
{
for(b=0;b<=9;b++)
{
d=(11*a+b)/10;
if((10*d)!=(11*a+b)) continue;
if(d>9) continue;
c=a+b-d;
if(c<0||c>9) continue;
result.Add(1000*a+100*b+10*c+d);
}
}
cn=result.Count;
sum = ((int[])(result.ToArray())).Sum();
uj5u.com熱心網友回復:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
int count = 0;
for (int i = 1000; i < 10000; i++)
{
if (Validate(i))
{
sum += i;
count++;
}
}
Console.WriteLine("滿足條件的四位自然數的個數為:{0}", count);
Console.WriteLine("滿足條件的四位自然數的和為:{0}", sum);
Console.ReadKey(true);
}
static bool Validate(int num)
{
int a = num % 10; // 個位數
int b = num / 10 % 10; // 十位數
int c = num / 100 % 10; // 百位數
int d = num / 1000; // 千位數
if (a + b == c + d && c + d == 10 * (a - d))
{
return true;
}
else
{
return false;
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/80485.html
標籤:C#
上一篇:如何將Form1中的textbox2里的內容傳到Form3中的textbox1中?
下一篇:C# 專案配置問題。
