最近臉書牆上一直出現這分享,就手癢寫了一下,後來順便複習一下國中數學?
原文連結
其實看到第一時間跟我本就忘記數學了,畢竟數學離我很遠了?(年紀大了),直覺就是想說這東西交給電腦就好啦
後來跑一下
var sp = new Stopwatch();
sp.Start();
Parallel.For(1, 10, a =>
{
Parallel.For(1, 10, b =>
{
Parallel.For(1, 10, c =>
{
Parallel.For(1, 10, d =>
{
long left = 25870 + a;
int right = (int)Math.Pow(2, b) * c * d * d * 11; // 2^b * c * d² * 11
if (left == right)
{
Console.WriteLine($"a={a}, b={b}, c={c}, d={d}, sum={left}");
}
});
});
});
});
Console.WriteLine(sp.Elapsed);
//a=2, b=3, c=6, d=7, sum=25872
//a=2, b=4, c=3, d=7, sum=25872
//00:00:00.0154183
有兩個答案 2367,2437 ,後來看一下面的留言,答案是 2437 為什麼呢?
因為 題目有講到 標準分解式 (原來有定義根本就壓根忘記 : 標準分解式是將一個合數表示成質數的乘積,並將相同質因數按照由小到大的順序,以指數形式表示的方法)
所以因數 c,d 都要為質數,則 b 為指數所以可以是 4
之後再修正一下
//簡單判斷是不是質數,反正在10以內,不可能太久
static bool IsPrime(int n)
{
if (n < 2) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
ststic void Calc(){
//計時器,非必要
var sp = new Stopwatch();
sp.Start();
Parallel.For(1, 10, a =>
{
Parallel.For(1, 10, b =>
{
Parallel.For(1, 10, c =>
{
Parallel.For(1, 10, d =>
{
// 檢查 c 是否是質數
if (!IsPrime(c))
return;
int left = 25870 + a;
int right = (int)Math.Pow(2, b) * c * d * d * 11; // 2^b * c * d² * 11
if (left == right)
{
lock (Console.Out)
Console.WriteLine($"a={a}, b={b}, c={c}, d={d}, sum={left}");
}
});
});
});
});
Console.WriteLine(sp.Elapsed);
//a=2, b=4, c=3, d=7, sum=25872
//00:00:00.0189032
}
很無聊就當練習一下,不過無聊的人好像不只有我一個,哈哈哈~~
