0

Problem:

Write an algorithm that asks the user to enter the number n of positive integers to be read, then reads these n integers and places them in an array so that first come the prime numbers, last the numbers even , and in between the numbers that are neither prime nor even .

In each group, the numbers must be placed according to their order of arrival.

For example, if the user enters the following numbers:

14, 23, 17, 18, 13, 15, 12, 3, 42, 21

then the table will be as follows:

23 17 13 3 15 21 14 18 12 42

My code:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace HelloWorld
{
public class Program
{
public static void Main(string[] args)
{int n, i, value, f, j, nbeven, nbprime, k,p,q, aux;
int[] t;
Console.WriteLine("give n:");
n=int.Parse(Console.ReadLine());
t=new int[n];
nbeven=0;nbprime=0;
for(i=0;i<n;i++)
   {
       Console.WriteLine("give value:");
       t[i]=int.Parse(Console.ReadLine());
       if(t[i]%2==0)
           nbeven=nbeven+1;
       else
           {
               f=2;
               for(j=2;j<=t[i]/2;i++)    
                  {
                   if(t[i]%j==0)
                     f=f+1;
                  } 
               if(f==2)  
                   nbprime=nbprime+1;                                             
           }                  
   }

k=0;p=0;q=0;
for(i=0;i<n;i++) 
   {
       if(t[i]%2==0)
        {
            aux=t[i];
            t[i]=t[n-nbeven+k];
            t[n-nbeven+k]=aux;
            k=k+1;
        } 
       else 
        {
            f=2;
            for(j=2;j<=t[i]/2;j++)
                {
                    if(t[i]%j==0)
                       f=f+1;
                    if(f==2)   
                       {
                           aux=t[i];
                           t[i]=t[p];
                           t[p]=aux;
                           p=p+1;                           
                       }
                    else
                       {
                           aux=t[i];
                           t[i]=t[nbprime+q];
                           t[nbprime+q]=aux;
                           q=q+1;
                       }   
                }
        }
   }               
for(i=0;i<n;i++)  
  Console.Write("{0} ",t[i]);
         
}
}
}
    
    
    

Error:

Unhandled exception: index was outside the bounds of the array.

Why am i getting this error?

  • 3
    Which line throws the exception? This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? – David Jun 28 '22 at 18:42
  • This is pedantic, forgive me, but in the Venn diagram of primes and evens, there is overlap. Your requirement that even numbers come after prime numbers does not consistently describe what should happen with the number 2. I think you meant _"last, the non-prime numbers that are even"._ – Wyck Jun 28 '22 at 19:23
  • Yes number 2 is an exception i didn't think about too much – Elie Makdissi Jun 28 '22 at 19:31

2 Answers2

3

I hope this code help you. Check this out

        int n, i;

        int[] t = { }, EvenArray = { }, oddArray = { }, primeArray = { };

        Console.WriteLine("give n:");
        n = int.Parse(Console.ReadLine());
        Array.Resize(ref t, n);

        //Inputs from user
        for (i = 0; i < n; i++)
        {
            Console.WriteLine("give value:");
            t[i] = int.Parse(Console.ReadLine());

        }

        //Check whether  anumber is prime or not
        bool isPrime(int n)
        {
            for (int i = 2; i < n / 2; i++)
            {
                if (n % i == 0)
                {
                    return false;
                }
            }
            return true;
        }

        //Linq Queries to retrieve odd and even numbers

        EvenArray = (from val in t where val % 2 == 0 && !isPrime(val) select val).ToArray();
        oddArray = (from val in t where val % 2 != 0 && !isPrime(val) select val).ToArray();

        //To assign prime numbers into primeArray
        for (int z = 0; z < n; z++)
        {

            if (isPrime(t[z]))
            {
                primeArray = primeArray.Concat(new int[] { t[z] }).ToArray();
            }
        }

        //Sorting Values in array
        Array.Sort(primeArray);
        Array.Sort(oddArray);
        Array.Sort(EvenArray);

    
        List<int> arrayList = new List<int> { };
        arrayList.AddRange(primeArray);
        arrayList.AddRange(oddArray);
        arrayList.AddRange(EvenArray);

        int[] result = new int[n];

        //Converting List to array
        result = arrayList.ToArray();

        Console.WriteLine("Ouptut");
        foreach (var res in result)
        {
            Console.Write($" {res}");
        } 
Pownraj.S
  • 126
  • 4
0

I suggest extracting methods, let IsPrime be the first

private static int IsPrime(int value) {
  if (value <= 1)
    return false;

  if (value % 2 == 0)
    return value == 2; // 2 is the only even prime number

  int n = (int)Math.Sqrt(value + 0.5);

  for (int divisor = 3; divisor <= n; divisor += 2)
    if (value % divisor == 0)
      return false;

  return true;
}

Next let us implement SortOrder: for each value we should decide if it's prime (should be put in begin of the array), even number (should be in the end of the array) or other number (somewhere in the middle).

private static int SortOrder(int value) {
  if (IsPrive(value))
    return 1; // Primes to be the first
  else if (value % 2 == 0)
    return 3; // Even to be the last
  else
    return 2; // Others are in the middle 
}

Ten you can easily sort the array:

int[] array = ...

Array.Sort(array, (left, right) => SortOrder(left) - SortOrder(right));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215