0

Code below works for stated number (6008514751), but throws up error for the desired Max value: 600851475143. I've used type long in place of 'int', so I don't see why my program is not able to run 600851475143. I would greatly appreciate any help.

Error thrown is: Unhandled Exception:
System.OverflowException: Arithmetic operation resulted in an overflow.
at HelloWorld.MakeSieve (System.Int64 max) [0x00000] in <0273ea83c32446be9aa2f9fc5d30dab0>:0
at HelloWorld.Main () [0x00000] in <0273ea83c32446be9aa2f9fc5d30dab0>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.OverflowException: Arithmetic operation resulted in an overflow.
at HelloWorld.MakeSieve (System.Int64 max) [0x00000] in <0273ea83c32446be9aa2f9fc5d30dab0>:0
at HelloWorld.Main () [0x00000] in <0273ea83c32446be9aa2f9fc5d30dab0>:0

*Update 1: Some of you suggested I take a look at "I need very big array length(size) in C#". I tried replacing my list with type double (even tried replacing all 'long' with 'double), to no avail.

Update 2: A trailing L (Max = 600851475143L) not helping much.

Thank you!

using System;
using System.Collections.Generic;

class HelloWorld
{

    public static long Max = 600851475;
    public static List<long> AllPrimesBelowMax = new List<long>();
    public static long maxPrime = 0;

    static void Main()
    {
        MakeSieve(Max);
    }

    private static bool[] MakeSieve(long max)
    {
        bool[] isPrime = new bool[max + 1];
        for (long i = 2; i <= max; i++)
        {
            isPrime[i] = true;
        }

        //cross out multiples
        for (long i = 2; i <= max; i++)
        {
            //check if i is prime
            if (isPrime[i] == true)
            {
                //cross out multiples of i
                for (long j = i * 2; j <= max; j += i)
                {
                    isPrime[j] = false;
                }
            }
        }

        for (long i = 2; i <= max; i++)
        {
            if (isPrime[i] == true)
            {
                AllPrimesBelowMax.Add(i);
            }
        }

        Console.WriteLine(AllPrimesBelowMax[AllPrimesBelowMax.Count - 1]);

        return isPrime;
    }
}
Adib0y360
  • 1
  • 5
  • You need to add a trailing L to the Max constant declaration. – kiwiron Feb 16 '20 at 00:45
  • @Julian As of now, no. I tried replacing 'long' with 'double', to no avail. Did I miss any key aspect of the solution provided in that post? – Adib0y360 Feb 16 '20 at 00:48
  • 600851475143 would need 600GB of memory, that is the root of the problem. But the error message is a bit confusing. – Antonín Lejsek Feb 16 '20 at 00:59
  • 1
    @Adib0y360 If you think the suggested duplicate indicated you needed to switch the data type, you need to read its top answer again. The problem is the size of the array. –  Feb 16 '20 at 01:00
  • Got it. Thank you! – Adib0y360 Feb 16 '20 at 01:04

0 Answers0