Monday, December 30, 2013

Project Euler Solution using C#: Problem 3: Largest Prime Factor

Problem:

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
My Solution:


  1. static void Main(string[] args)
  2. {
  3.             const long constantInput = 600851475143;
  4.             long input = constantInput;
  5.             long divider = 2;
  6.             long multiplyList = 1;
  7.             bool largestPrimeFound = false;
  8.             while (largestPrimeFound == false)
  9.             {
  10.                 if (input % divider == 0)
  11.                 {
  12.                     long val = input / divider;
  13.                     input = val;
  14.                     Console.WriteLine(divider);
  15.                     multiplyList *= divider;
  16.                     if (multiplyList == constantInput)
  17.                     {
  18.                         Console.WriteLine("The largest prime factor for the number " + constantInput + " is : " + divider);
  19.                         largestPrimeFound = true;
  20.                     }
  21.                 }
  22.                 else
  23.                 {
  24.                     divider += 1;
  25.                 }
  26.             }
  27.             Console.ReadLine();
  28. }
Note: You can simplifies the coding :)

No comments:

Post a Comment