# Overflow exception while performing parallel factorization using the .NET Task Parallel Library (TPL

Filed under:
|
##### overflow
|

Hello, I'm trying to write a not so smart factorization program and trying to do it in parallel using TPL. However, after about 15 minutes of running on a core 2 duo machine, I am getting an aggregate exception with an overflow exception inside it. All the entries in the stack trace are part of the .NET framework, the overflow does not come from my code. Any help would be appreciated in figuring out why this happens.

Here's the commented code, hopefully it's simple enough to understand:

``````class Program
{
static List<Tuple<BigInteger, int>> factors = new List<Tuple<BigInteger, int>>();

static void Main(string[] args)
{
BigInteger theNumber = BigInteger.Parse(
"653872562986528347561038675107510176501827650178351386656875178" +
"568165317809518359617865178659815012571026531984659218451608845" +
"719856107834513527");
Stopwatch sw = new Stopwatch();
bool isComposite = false;
sw.Start();

do
{
/* Print out the number we are currently working on. */
Console.WriteLine(theNumber);

/* Find a factor, stop when at least one is found
(using the Any operator). */
isComposite = Range(theNumber)
.AsParallel()
.Any(x => CheckAndStoreFactor(theNumber, x));

/* Of the factors found, take the one with the lowest base. */
var factor = factors.OrderBy(x => x.Item1).First();
Console.WriteLine(factor);

/* Divide the number by the factor. */
theNumber = BigInteger.Divide(
theNumber,
BigInteger.Pow(factor.Item1, factor.Item2));

/* Clear the discovered factors cache, and keep looking. */
factors.Clear();
} while (isComposite);

sw.Stop();
Console.WriteLine(isComposite + " " + sw.Elapsed);
}

static IEnumerable<BigInteger> Range(BigInteger squareOfTarget)
{
BigInteger two = BigInteger.Parse("2");
BigInteger element = BigInteger.Parse("3");
while (element * element < squareOfTarget)
{
yield return element;
}
}

static bool CheckAndStoreFactor(BigInteger candidate, BigInteger factor)
{
BigInteger remainder, dividend = candidate;
int exponent = 0;
do
{
dividend = BigInteger.DivRem(dividend, factor, out remainder);
if (remainder.IsZero)
{
exponent++;
}
} while (remainder.IsZero);
if (exponent > 0)
{
lock (factors)
{
}
}
return exponent > 0;
}
}
``````

Here's the exception thrown:

``````Unhandled Exception: System.AggregateException: One or more errors occurred. ---
> System.OverflowException: Arithmetic operation resulted in an overflow.
at System.Linq.Parallel.PartitionedDataSource`1.ContiguousChunkLazyEnumerator.MoveNext(T& currentElement, Int32& currentKey)
at System.Linq.Parallel.AnyAllSearchOperator`1.AnyAllSearchOperatorEnumerator`1.MoveNext(Boolean& currentElement, Int32& currentKey)
--- End of inner exception stack trace ---
at System.Linq.Parallel.DefaultMergeHelper`2.System.Linq.Parallel.IMergeHelper<TInputOutput>.Execute()
at System.Linq.Parallel.MergeExecutor`1.Execute[TKey](PartitionedStream`2 partitions, Boolean ignoreOutput, ParallelMergeOptions options, TaskScheduler taskScheduler, Boolean isOrdered, CancellationState cancellationState, Int32 queryId)

at System.Linq.Parallel.AnyAllSearchOperator`1.WrapPartitionedStream[TKey](PartitionedStream`2 inputStream, IPartitionedStreamRecipient`1 recipient, BooleanpreferStriping, QuerySettings settings)
at System.Linq.Parallel.ScanQueryOperator`1.ScanEnumerableQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient)
at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient)
at System.Linq.Parallel.QueryOperator`1.GetOpenedEnumerator(Nullable`1 mergeOptions, Boolean suppressOrder, Boolean forEffect, QuerySettings querySettings)
at System.Linq.Parallel.QueryOpeningEnumerator`1.OpenQuery()
at System.Linq.Parallel.QueryOpeningEnumerator`1.MoveNext()
at System.Linq.Parallel.AnyAllSearchOperator`1.Aggregate()
at System.Linq.ParallelEnumerable.Any[TSource](ParallelQuery`1 source, Func`2 predicate)
at PFact.Program.Main(String[] args) in d:\myprojects\PFact\PFact\Program.cs:line 34
``````

Any help would be appreciated.

Thanks!

© Stack Overflow or respective owner

• #### .NET WebRequest.PreAuthenticate not quite what it sounds like

as seen on West-Wind - Search for 'West-Wind'
I’ve run into the  problem a few times now: How to pre-authenticate .NET WebRequest calls doing an HTTP call to the server – essentially send authentication credentials on the very first request instead of waiting for a server challenge first? At first glance this sound like it should be easy:… >>> More

• #### HttpWebRequest and Ignoring SSL Certificate Errors

as seen on West-Wind - Search for 'West-Wind'
Man I can't believe this. I'm still mucking around with OFX servers and it drives me absolutely crazy how some these servers are just so unbelievably misconfigured. I've recently hit three different 3 major brokerages which fail HTTP validation with bad or corrupt certificates at least according to… >>> More

• #### Dynamic Type to do away with Reflection

as seen on West-Wind - Search for 'West-Wind'
The dynamic type in C# 4.0 is a welcome addition to the language. One thing I’ve been doing a lot with it is to remove explicit Reflection code that’s often necessary when you ‘dynamically’ need to walk and object hierarchy. In the past I’ve had a number of ReflectionUtils that used string based expressions… >>> More

• #### The dynamic Type in C# Simplifies COM Member Access from Visual FoxPro

as seen on West-Wind - Search for 'West-Wind'
I’ve written quite a bit about Visual FoxPro interoperating with .NET in the past both for ASP.NET interacting with Visual FoxPro COM objects as well as Visual FoxPro calling into .NET code via COM Interop. COM Interop with Visual FoxPro has a number of problems but one of them at least got a lot… >>> More

• #### Finding a Relative Path in .NET

as seen on West-Wind - Search for 'West-Wind'
Here’s a nice and simple path utility that I’ve needed in a number of applications: I need to find a relative path based on a base path. So if I’m working in a folder called c:\temp\templates\ and I want to find a relative path for c:\temp\templates\subdir\test.txt I want to receive back subdir\test… >>> More

• #### Buffer Overflow (vs) Buffer OverRun (vs) Stack Overflow [closed]

as seen on Stack Overflow - Search for 'Stack Overflow'
Possible Duplicate: What is the difference between a stack overflow and buffer overflow ? What is the difference between Buffer Overflow and Buffer Overrun? What is the difference between Buffer Overrun and Stack Overflow? Please include code examples. I have looked at the terms in Wikipedia… >>> More

• #### Checking for underflow/overflow in C++?

as seen on Stack Overflow - Search for 'Stack Overflow'
Is there a general way to check for an overflow or an underflow of a given data type (uint32, int etc.)? I am doing something like this: uint32 a,b,c; ... //initialize a,b,c if(b < c) { a -= (c - b) } When I print a after some iterations, it displays a large number like: 4294963846. >>> More

• #### Using logarithms to normalize a vector to avoid overflow

as seen on Stack Overflow - Search for 'Stack Overflow'
http://stackoverflow.com/questions/2293762/problem-with-arithmetic-using-logarithms-to-avoid-numerical-underflow-take-2 Having seen the above and having seen softmax normalization I was trying to normalize a vector while avoiding overflow - that is (x1 x2 x3 x4 ... xn) the normalized form for me… >>> More

• #### Extra text shown on oveflow: hidden

as seen on Stack Overflow - Search for 'Stack Overflow'
I'm keeping the main content area of the webpage small, so that footer navigation can be seen "above the fold". This is done by javascript setting the main content <div> thus: sec.style.height = '265px'; sec.style.overflow = 'hidden'; And then using javascript to insert a button to change… >>> More

• #### A lot of TCP: time wait bucket table overflow in CentOS 6

as seen on Server Fault - Search for 'Server Fault'
we have the following output from dmesg: __ratelimit: 33491 callbacks suppressed TCP: time wait bucket table overflow TCP: time wait bucket table overflow TCP: time wait bucket table overflow TCP: time wait bucket table overflow TCP: time wait bucket table overflow TCP: time wait bucket table overflow TCP:… >>> More