Advertisement
DarthGizka

vet_reference_primes_up_to_64k.linq

Apr 29th, 2016
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 KB | None | 0 0
  1. // vet_reference_primes_up_to_64k.linq
  2. // 2016-04-29
  3. //
  4. // https://primes.utm.edu/lists/small/10000.txt
  5. // http://pari.math.u-bordeaux.fr/gp.html
  6. //    forprime(p = 2, 2^16, print(p))
  7. //    primes(6542)
  8. //
  9. // see http://codereview.stackexchange.com/q/127024/56653
  10.  
  11. const string ReferenceFile = "reference_primes_up_to_64k.txt";       // <-- file to be vetted
  12. const string First10K = "d:/dev/cpp/algo/primes/common/10000.txt";   // <-- downloaded file vetted against
  13.  
  14. void Main ()
  15. {
  16.     var primes = System.IO.File.ReadAllLines(ReferenceFile).Select(ushort.Parse).ToList();
  17.  
  18.     assert_equal("count", 6542, primes.Count);
  19.    
  20.     var sum = primes.Select((p) => (int)p).Sum();
  21.    
  22.     assert_equal("sum", 202288087, sum);
  23.    
  24.     var primorial_64bit = primes.Select((p) => (ulong)p).Aggregate((product, prime) => product * prime);
  25.  
  26.     assert_equal("product", 8987519195527561682UL, primorial_64bit);
  27.  
  28.     if (!primes.SequenceEqual(read_primes_up_to_64K_from_utm_edu_file()))
  29.         throw new Exception("!primes.SequenceEqual(read_primes_up_to_64K_from_utm_edu_file())");
  30.  
  31.     Console.Write("{0} vetted successfully", ReferenceFile);
  32.  
  33.     var current_attributes = System.IO.File.GetAttributes(ReferenceFile);
  34.  
  35.     if ((current_attributes & FileAttributes.ReadOnly) == 0)
  36.     {
  37.         Console.Write(" - making the file read-only");
  38.        
  39.         System.IO.File.SetAttributes(ReferenceFile, current_attributes | FileAttributes.ReadOnly);
  40.     }
  41. }
  42.  
  43. static void assert_equal<T> (string what, T expected, T value)
  44. {
  45.     if (!EqualityComparer<T>.Default.Equals(value, expected))
  46.         throw new Exception(string.Format("{0}: expected {1}, got {2}", what, expected, value));
  47. }
  48.  
  49. static List<ushort> read_primes_up_to_64K_from_utm_edu_file (string filename = First10K)
  50. {
  51.     var result = new List<ushort>();
  52.  
  53.     foreach (var line in System.IO.File.ReadAllLines(filename).Select((s) => s.Trim()))
  54.     {
  55.         if (line.Length > 0 && char.IsDigit(line[0]))
  56.         {
  57.             var numbers = line.Split(' ')
  58.                     .Where((x) => x.Length > 0)
  59.                     .Select(int.Parse)
  60.                     .Where((x) => x <= ushort.MaxValue)
  61.                     .Select((x) => (ushort)x);
  62.            
  63.             result.AddRange(numbers);
  64.         }
  65.     }
  66.  
  67.     return result;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement