diff --git a/PerfectNumbers.Core/PrimeOrderCalculator.cs b/PerfectNumbers.Core/PrimeOrderCalculator.cs index f139cee..2f4da94 100644 --- a/PerfectNumbers.Core/PrimeOrderCalculator.cs +++ b/PerfectNumbers.Core/PrimeOrderCalculator.cs @@ -1,6 +1,7 @@ using System.Buffers; using System.Buffers.Binary; using System.Diagnostics; +using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using PerfectNumbers.Core.Gpu; @@ -331,23 +332,19 @@ internal static partial class PrimeOrderCalculator ArrayPool factorPool = FactorPool; FactorEntry[]? tempArray = null; + ReadOnlySpan factorSpan = factors.Factors; + int length = factors.Count; + int capacity = length + 1; + + Span buffer = capacity <= FactorEntryStackThreshold ? stackalloc FactorEntry[capacity] : default; + if (capacity > FactorEntryStackThreshold) + { + tempArray = factorPool.Rent(capacity); + buffer = tempArray.AsSpan(0, capacity); + } + try { - ReadOnlySpan factorSpan = factors.Factors; - int length = factors.Count; - int capacity = length + 1; - - Span buffer; - if (capacity <= FactorEntryStackThreshold) - { - buffer = stackalloc FactorEntry[capacity]; - } - else - { - tempArray = factorPool.Rent(capacity); - buffer = tempArray.AsSpan(0, capacity); - } - factorSpan.CopyTo(buffer); bool isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(factors.Cofactor); diff --git a/PerfectNumbers.Core/ULongExtensions.cs b/PerfectNumbers.Core/ULongExtensions.cs index a2ed557..fca8662 100644 --- a/PerfectNumbers.Core/ULongExtensions.cs +++ b/PerfectNumbers.Core/ULongExtensions.cs @@ -347,14 +347,10 @@ public static class ULongExtensions ulong result = divisor.MontgomeryOne; ulong nPrime = divisor.NPrime; - Span oddPowerStorage; + Span oddPowerStorage = oddPowerCount <= PerfectNumberConstants.MaxOddPowersCount ? stackalloc ulong[PerfectNumberConstants.MaxOddPowersCount] : default; ulong[]? pooledOddPowers = null; - if (oddPowerCount <= PerfectNumberConstants.MaxOddPowersCount) - { - oddPowerStorage = stackalloc ulong[PerfectNumberConstants.MaxOddPowersCount]; - } - else if (oddPowerCount < PerfectNumberConstants.PooledArrayThreshold) + if (oddPowerCount < PerfectNumberConstants.PooledArrayThreshold) { oddPowerStorage = new ulong[oddPowerCount]; }