5
난에서 다음 콜라 츠 추측 알고리즘을 변환하려합니다
public class CollatzConjexture
{
public static int Calculate(int StartIndex, int MaxSequence)
{
int ChainLength = 0;
int key = 0;
bool ContinuteCalulating = true;
int LongestChain = 0;
Int64 Remainder = 0;
for (int i = StartIndex; i <= MaxSequence; i++)
{
ChainLength = 1;
Remainder = i;
ContinuteCalulating = true;
while (ContinuteCalulating)
{
Remainder = CalculateCollatzConjecture(Remainder);
if (Remainder == 1)
ContinuteCalulating = false;
ChainLength += 1;
}
if (ChainLength > LongestChain)
{
LongestChain = ChainLength;
key = i;
}
}
return key;
}
private static Int64 CalculateCollatzConjecture(Int64 Number)
{
if (Number % 2 == 0)
return Number/2;
else
return (3 * Number) + 1;
}
}
대신 .NET 4.0 Parallel.For 사용하려면 : 나는 '느낌이
int ChainLength = 0;
int key = 0;
bool ContinuteCalulating = true;
int LongestChain = 0;
Int64 Remainder = 0;
int[] nums = Enumerable.Range(1, 1500000).ToArray();
long total = 0;
// Use type parameter to make subtotal a long, not an int
Parallel.For<int>(1, nums.Length,() => 1, (j, loop, subtotal) =>
{
Remainder = j;
while (ContinuteCalulating)
{
Remainder = CalculateCollatzConjecture(Remainder);
if (Remainder == 1)
ContinuteCalulating = false;
ChainLength += 1;
}
if (ChainLength > LongestChain)
{
LongestChain = ChainLength;
key = j;
}
return key;
},
(x) => Interlocked.Add(ref key, x)
);
을 그다지 멀지 않은 유명한 마지막 단어들.
미리 감사드립니다.
실행할 때 가장 긴 Collatz 체인을 생성하는 가장 작은 인덱스를 얻을 필요는 없습니다 (즉, 1에서 1500000, 직렬 메서드는 1117065 및 LINQ 메서드 1126015를 반환하며 둘 다 체인 길이가 528입니다.). LINQ를 배우는 중이므로'.Aggregate' 호출을 수정하여이 문제를 해결할 수있는 간단한 방법이 있습니까? – chezy525
어떻게 든 디버깅 할 때 (1117065, 1126015) 별도의 경우에 두 가지 대답을 얻고 있습니다. 이상적으로, 나는 최소 지수를 원합니다. 미리 감사드립니다. – Seany84
이것으로 조금 놀아본 후'.Aggregate'에서 조건문을 변경하기 만하면된다고 생각합니다. 즉,'max.len cur.key)' –
chezy525