Write a program in C# to find the largest prime among a collection of numbers

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 1231
Let's say that we have a collection of integers as {104723, 104729, 9998,448 }. Objective is to find the largest prime among a collection of numbers. The below program will do so

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var numberCollection = new List<int>() {104723, 104729, 9998,448 };
var nonPrimeCollection = new List<int>();

for (int j = 0; j < numberCollection.Count; j++)
{
for (int i = 2; i < numberCollection[j]; i++)
{
if (numberCollection[j] % i == 0)
{
nonPrimeCollection.Add(numberCollection[j]);
break;
}
}
}
Console.WriteLine("Largest Prime {0} ", numberCollection.Except(nonPrimeCollection).Max());
Console.ReadKey();
}
}
}


Result
--------
Largest Prime 104729


The outer for loop is looping thru the entire collection. The inner for loop starts at 2 and picks up those elements that are not primes. And then we are finding the numbers which are prime and finally finding the max.

Comments or Responses

Login to post response