本帖最后由 轩墨玉生烟 于 2016-3-20 15:49 编辑
在我祭出源代码之前,还是给大家科普一下什么是完数。完数,也就是完全数(Perfect number),又称完美数或完备数,是一些特殊的自然数。它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。如果一个数恰好等于它的因子之和,则称该数为“完全数”。
这个程序在某些方面而言,可以说能够拿来测试当前计算机的CPU的性能,如果你想试一试,不妨将下面的源代码复制粘贴后跑一下吧:
1、C#版本的源代码:
[C#] 纯文本查看 复制代码 using System.Threading.Tasks;
class MainConWin32
{
private uint Sum = 0;
void Main()
{
private const string vbCrLf = "\n";
Action serialFor = () =>
{
Console.WriteLine(new string(vbCrLf + "[" + Now + "] Serial Operation..."));
for (uint Number = 2; Number <= uint.MaxValue; Number += 1) {
for (uint Div = 1; Div <= Number - 1; Div += 1) {
if (Number % Div == 0) {
Sum = Sum + Div;
}
}
if (Sum == Number)
Console.WriteLine(Number + Space(3) + "Time=" + TimeOfDay);
Sum = 0;
}
};
Action parallelFor = () =>
{
Console.WriteLine(new string(vbCrLf + "[" + Now + "] Parallel Operation..."));
Parallel.For(2, uint.MaxValue + 1, index =>
{
Parallel.For(1, index, s_index =>
{
if (index % s_index == 0) {
Sum = Sum + s_index;
}
});
if (Sum == index)
Console.WriteLine(index + " " + "Time=" + DateTime.TimeOfDay);
Sum = 0;
});
};
Console.WriteLine(new string("找完数" + vbCrLf));
Console.Write(new string("请选择执行操作的方式 ( 0=并行计算,1=串行计算 ):"));
char readChar = Convert.ToInt32(Console.Read(), 10);
if (readChar == "0") {
Task.Factory.StartNew(parallelFor).Wait();
} else if (readChar == "1") {
Task.Factory.StartNew(serialFor).Wait();
} else {
Console.WriteLine(new string(vbCrLf + "选择错误,默认将执行串行操作!!!"));
Task.Factory.StartNew(serialFor).Wait();
}
}
}
2、VB.NET版本的源代码:
[Visual Basic .NET] 纯文本查看 复制代码 Imports System.Threading.Tasks
Module MainConWin32
Private Sum As UInteger = 0
Sub Main()
Dim serialFor As Action = Sub()
Console.WriteLine(New String(vbCrLf & "[" & Now & "] Serial Operation..."))
For Number As UInteger = 2 To UInteger.MaxValue Step 1
For Div As UInteger = 1 To Number - 1 Step 1
If Number Mod Div = 0 Then
Sum = Sum + Div
End If
Next Div
If Sum = Number Then Console.WriteLine(Number & Space(3) & "Time=" & TimeOfDay)
Sum = 0
Next Number
End Sub
Dim parallelFor As Action = Sub()
Console.WriteLine(New String(vbCrLf & "[" & Now & "] Parallel Operation..."))
Parallel.For(2, UInteger.MaxValue + 1, _
Sub(index)
Parallel.For(1, index, Sub(s_index)
If index Mod s_index = 0 Then
Sum = Sum + s_index
End If
End Sub)
If Sum = index Then Console.WriteLine(index & Space(3) & "Time=" & TimeOfDay)
Sum = 0
End Sub)
End Sub
Console.WriteLine(New String("找完数" & vbCrLf))
Console.Write(New String("请选择执行操作的方式 ( 0=并行计算,1=串行计算 ):"))
Dim readChar As Char = ChrW(Console.Read)
If readChar = "0" Then
Task.Factory.StartNew(parallelFor).Wait()
ElseIf readChar = "1" Then
Task.Factory.StartNew(serialFor).Wait()
Else
Console.WriteLine(New String(vbCrLf & "选择错误,默认将执行串行操作!!!"))
Task.Factory.StartNew(serialFor).Wait()
End If
End Sub
End Module
当然,这个程序里面包含了串行和并行两种方式求完数,所以在测试的时候不妨两样方法都测试一下吧!
serialFor是串行求完数,parallelFor是并行求完数。
|