Author Topic: C# program to print twin prime numbers  (Read 2185 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
C# program to print twin prime numbers
« on: November 28, 2011, 06:07:19 pm »
Here is the c# program to print the twin prime numbers under 1000. You can increase or decrease this limit by simply changing the value condition in the for loop.

Code: (C#)
//Source Code Listing

using System;
using System.Collections.Generic;
using System.Text;

namespace SoftwareAndFinance
{
   class Math
   {
      static bool IsPrimeNumber(int num)
      {
         bool bPrime = true;
         int factor = num / 2;

         int i = 0;

         for (i = 2; i <= factor; i++)
         {
            if ((num % i) == 0)
               bPrime = false;
         }
         return bPrime;
      }

      static void Main(string[] args)
      {

         int firstprime = 0, secondprime = 0, totalTwinPrimeNumbers = 0;

         Console.WriteLine("List of Twin prime numbers under 1000");

         for (int i = 2; i <= 1000; i++)
         {
            if (IsPrimeNumber(i) == true)
            {
               if (firstprime == 0)
                  firstprime = i;
               else
                  secondprime = i;
               bool IsTwinPrimeNumber = ((secondprime - firstprime) == 2);
               if (IsTwinPrimeNumber == true)
               {
                  Console.Write("{0,3}, {1,3}\n", firstprime, secondprime);
                  totalTwinPrimeNumbers++;
               }
               secondprime = firstprime = i;
            }
         }
         Console.WriteLine("Total number of twin prime numbers under 1000: {0}\n\n", totalTwinPrimeNumbers);
      }
   }
}

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1