Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.25 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5.  
  6. namespace euler
  7. {
  8.     class Program
  9.     {
  10.  
  11.         public static void Main(string[] args)
  12.         {
  13.             new Program().BruteForce();
  14.         }
  15.  
  16.         public void BruteForce()
  17.         {
  18.             Stopwatch clock = Stopwatch.StartNew();
  19.  
  20.             int[] primeList = ESieve(10000);
  21.  
  22.             int result = 1;
  23.             bool notFound = true;
  24.  
  25.             while (notFound)
  26.             {
  27.                 result += 2;
  28.  
  29.                 int j = 0;
  30.                 notFound = false;
  31.                 while (result >= primeList[j])
  32.                 {
  33.                     if (isTwiceSquare(result - primeList[j]))
  34.                     {
  35.                         notFound = true;
  36.                         break;
  37.                     }
  38.                     j++;
  39.                 }
  40.             }
  41.  
  42.             clock.Stop();
  43.             Console.WriteLine("The smallest counter example is {0}", result);
  44.             Console.WriteLine("Solution took {0} ms", clock.ElapsedMilliseconds);
  45.         }
  46.  
  47.  
  48.         private bool isTwiceSquare(long number)
  49.         {
  50.             double squareTest = Math.Sqrt(number / 2);
  51.             return squareTest == ((int)squareTest);
  52.         }
  53.  
  54.         public int[] ESieve(int upperLimit)
  55.         {
  56.  
  57.             int sieveBound = (int)(upperLimit - 1) / 2;
  58.             int upperSqrt = ((int)Math.Sqrt(upperLimit) - 1) / 2;
  59.  
  60.             BitArray PrimeBits = new BitArray(sieveBound + 1, true);
  61.  
  62.             for (int i = 1; i <= upperSqrt; i++)
  63.             {
  64.                 if (PrimeBits.Get(i))
  65.                 {
  66.                     for (int j = i * 2 * (i + 1); j <= sieveBound; j += 2 * i + 1)
  67.                     {
  68.                         PrimeBits.Set(j, false);
  69.                     }
  70.                 }
  71.             }
  72.  
  73.             List<int> numbers = new List<int>((int)(upperLimit / (Math.Log(upperLimit) - 1.08366)));
  74.             numbers.Add(2);
  75.             for (int i = 1; i <= sieveBound; i++)
  76.             {
  77.                 if (PrimeBits.Get(i))
  78.                 {
  79.                     numbers.Add(2 * i + 1);
  80.                 }
  81.             }
  82.  
  83.             return numbers.ToArray();
  84.         }
  85.     }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement