Tuesday, January 21, 2014

Project Euler Solution using C#: Problem 5: Smallest Multiple

Problem:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
My Solution:

  1.        static void Main(string[] args)
  2.         {
  3.             int num = 1;
  4.             bool isDivisiblyByAll = false;
  5.             bool isFound = false;
  6.             while (isFound == false)
  7.             {
  8.                 for (int i = 1; i <= 20; i++)
  9.                 {
  10.                     if (num % i == 0)
  11.                     {
  12.                         isDivisiblyByAll = true;
  13.                     }
  14.                     else
  15.                     {
  16.                         isDivisiblyByAll = false;
  17.                         break;
  18.                     }
  19.                 }
  20.                 if (isDivisiblyByAll)
  21.                 {
  22.                     isFound = true;
  23.                     Console.WriteLine("Smallest positive number that is evenly divisible by all of the numbers from 1 to 20 is : " + num);
  24.                 }
  25.                 num++;
  26.             }
  27.             Console.ReadLine();
  28.         }
Note: You can simplifies the coding :)

No comments:

Post a Comment