fork(1) download
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System.Threading.Tasks;
  5.  
  6. public static class Test
  7. {
  8. public static void Main()
  9. {
  10. int max = int.Parse(Console.ReadLine());
  11. double zeta2 = Primes(max).Aggregate(1d, (r, p) => r / (1 - 1d / p / p));
  12. Console.WriteLine(zeta2);
  13. }
  14.  
  15. private static IEnumerable<int> Primes(int max)
  16. {
  17. if (max < 5)
  18. {
  19. return Enumerable.Range(2, Math.Clamp(max - 1, 0, 2));
  20. }
  21. else
  22. {
  23. return new PrimesCalculator(max).PrimesAsync().Result;
  24. }
  25. }
  26. }
  27.  
  28. internal sealed class PrimesCalculator
  29. {
  30. const int start = 2;
  31.  
  32. internal PrimesCalculator(int max)
  33. {
  34. array = new bool[max + 1];
  35. end = ((int)Math.Sqrt(max) + 2) / 3;
  36. tasks = new Task[end + 1];
  37. removeAction = Remove;
  38. result = Enumerate(array);
  39. }
  40.  
  41. internal async Task<IEnumerable<int>> PrimesAsync()
  42. {
  43. if (n == start)
  44. {
  45. RunRemove();
  46. while (n <= end)
  47. {
  48. await Task.Delay(32);
  49. }
  50. await Task.WhenAll(tasks.Where(t => t != null));
  51. }
  52. return result;
  53. }
  54.  
  55. private static int Generator(int n) => (n & ~1) + (n << 1) - 1;
  56.  
  57. private static IEnumerable<int> Enumerate(bool[] array)
  58. {
  59. yield return 2;
  60. yield return 3;
  61. int value;
  62. for (int k = 2; (value = Generator(k)) < array.Length; k++)
  63. {
  64. if (!array[value])
  65. {
  66. yield return value;
  67. }
  68. }
  69. }
  70.  
  71. private readonly bool[] array;
  72.  
  73. private int n = start;
  74.  
  75. private readonly int end;
  76.  
  77. private readonly Task[] tasks;
  78.  
  79. private readonly Action removeAction;
  80.  
  81. private readonly IEnumerable<int> result;
  82.  
  83. private void RunRemove()
  84. {
  85. if (n <= end)
  86. {
  87. ref var task = ref tasks[n];
  88. task = new Task(removeAction);
  89. task.Start();
  90. }
  91. }
  92.  
  93. private void Remove()
  94. {
  95. int prime;
  96. while (array[prime = Generator(n++)]) ;
  97. int k = n - 1;
  98. ref var isComposite = ref array[prime];
  99. RunRemove();
  100. int composite;
  101. for (; !isComposite && (composite = Generator(k) * prime) < array.Length; k++)
  102. {
  103. array[composite] = true;
  104. }
  105. }
  106. }
Success #stdin #stdout 0.58s 105272KB
stdin
77777777
stdout
1.64493406577072