Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Diagnostics;
- using System.Linq;
- namespace ConsoleApplication1
- {
- class Program
- {
- static Primes primes;
- class Primes
- {
- public HashSet<int> all_numbers = new HashSet<int>();
- public HashSet<int> list_of_primes = new HashSet<int>();
- public HashSet<int> list_of_nonprimes = new HashSet<int>();
- public Primes(int n)
- {
- all_numbers = new HashSet<int>(Enumerable.Range(1, n));
- for (int i = 2; i < Math.Sqrt(n) + 1; i++)
- {
- for (int j = 3; j <= n / i; j++)
- list_of_nonprimes.Add(i * j);
- }
- list_of_primes = new HashSet<int>(all_numbers.Except(list_of_nonprimes));
- }
- }
- static void Main(string[] args)
- {
- Stopwatch t = new Stopwatch();
- t.Reset();
- t.Start();
- Console.WriteLine(FindMaxCoeff());
- t.Stop();
- Console.WriteLine(t.ElapsedMilliseconds);
- t.Start();
- primes = new Primes(1000);
- Console.WriteLine(FindMaxCoeff2());
- t.Stop();
- Console.WriteLine(t.ElapsedMilliseconds);
- Console.ReadKey();
- }
- static int FindMaxCoeff()
- {
- int maxConsec = 0;
- int maxCoeff = 0;
- for (int a = -999; a < 1000; a++)
- {
- for (int b = -999; b < 1000; b++)
- {
- int currentConsec = FindMaxConsecutive(a, b);
- if (currentConsec > maxConsec)
- {
- maxConsec = currentConsec;
- maxCoeff = a * b;
- }
- }
- }
- return maxCoeff;
- }
- static int FindMaxConsecutive(int a, int b)
- {
- int n = 0;
- for (n = 0; IsPrime(n * n + a * n + b); n++) ;
- return n;
- }
- static bool IsPrime(int n)
- {
- n = Math.Abs(n);
- if (n == 1 || n == 2 || n == 3)
- {
- return true;
- }
- if (n % 2 == 0 || n % 3 == 0)
- {
- return false;
- }
- for (int x = 6; x - 1 <= Math.Sqrt(n); x += 6)
- {
- if (n % (x - 1) == 0 || n % (x + 1) == 0)
- {
- return false;
- }
- }
- return true;
- }
- static int FindMaxCoeff2()
- {
- int maxConsec = 0;
- int maxCoeff = 0;
- for (int a = -999; a < 1000; a++)
- {
- for (int b = -999; b < 1000; b++)
- {
- int currentConsec = FindMaxConsecutive2(a, b);
- if (currentConsec > maxConsec)
- {
- maxConsec = currentConsec;
- maxCoeff = a * b;
- }
- }
- }
- return maxCoeff;
- }
- static int FindMaxConsecutive2(int a, int b)
- {
- int n = 0;
- for (n = 0; primes.list_of_primes.Contains(n * n + a * n + b); n++) ;
- return n;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement