0

I am having trouble with a problem that will tell me if a number is prime or not. I am passing every test but the random test. I am an entry level dev so it may not be pretty but I would like help on how to get this to pass a test even if the number is "1008985750798" for example...

public static bool IsPrime(int n)
{   
    bool returnMe = true;

    if (n% 2 == 0 || n % 3 == 0 || n <= 1)
    {  
        returnMe = false;
    }
    if (n % 2 == 0 && n % 3 == 0)
    {
        returnMe = false; 
    } 
    if ( n == 2 || n == 3 || n == 7)
    {
        returnMe = true;     
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 2
    Use `long` or even `BigInteger` if you want even larger values. `int` can only handle up to 2^31-1... which is 2.something billion. – itsme86 Oct 17 '19 at 21:25
  • Read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ for tips on how to debug your code. – Code-Apprentice Oct 17 '19 at 21:29
  • You wouldn't be able to pass that number to `IsPrime`. Limit your random number to the valid values for `int` (between `int.MinValue` and `int.MaxValue`). – Heretic Monkey Oct 17 '19 at 21:29
  • https://stackoverflow.com/questions/15743192/check-if-number-is-prime-number – Sach Oct 17 '19 at 21:36

1 Answers1

-1

While Program to find prime numbers shows a nice, efficient implementation I think you are after something that is easier to understand.

Here's a naive approach:

public static void Main()
{
    for(uint i = 0; i < 1000; i++) {
        if (IsPrime(i)) Console.Write($"{i},");
    }
}

private static bool IsPrime(uint n)
{
   if (n < 3) return false;
   for (uint i = 2; i < n; i++)
       if (n % i == 0) return false;
   return true;
}

If you want to go a bit faster, let's ask Wikipedia for help.

/// <summary>
/// Tests the number for primality. It is a c# version of the pseudocode from 
/// https://en.wikipedia.org/wiki/Primality_test
/// </summary>
private static bool IsPrime2(uint n)
{
    // The following is a simple primality test in pseudocode using 
    // the simple 6k ± 1 optimization mentioned earlier. 
    // More sophisticated methods described below are much faster for large n. 
    if (n <= 3)
        return n > 1;
    if (n % 2 == 0 || n % 3 == 0)
        return false;
    uint i = 5;
    while (i * i <= n)
    {
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
        i = i + 6;
    }
    return true;
}
tymtam
  • 31,798
  • 8
  • 86
  • 126