n-esimo primo problema numero, hanno bisogno di accelerarlo un po '
-
06-09-2019 - |
Domanda
Non v'è sistema di cifratura che traduce il numero di serie di . ( )
Al fine di Encrypt un numero (0 .. 2147483647) per questa rappresentazione, I (penso I) necessità:
- Primo fattorizzazione
- per proposta p ( p è Prime), sequenza di ordine p (es. PrimeOrd (2) == 0 , PrimeOrd (227) == 49 )
Alcuni esempi
0 . 6 (()()) 1 () 7 (...()) 2 (()) 8 ((.())) 3 (.()) 9 (.(())) 4 ((())) 10 (().()) 5 (..()) 11 (....()) 227 (................................................()) 2147483648 ((..........()))
Il mio codice sorgente per il problema
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
static class P
{
static List<int> _list = new List<int>();
public static int Nth(int n)
{
if (_list.Count == 0 || _list.Count < n)
Primes().Take(n + 1);
return _list[n];
}
public static int PrimeOrd(int prime)
{
if (_list.Count == 0 || _list.Last() < prime)
Primes().First(p => p >= prime);
return (_list.Contains(prime)) ? _list.FindIndex(p => p == prime) : -1;
}
public static List<int> Factor(int N)
{
List<int> ret = new List<int>();
for (int i = 2; i ≤ N; i++)
while (N % i == 0)
{
N /= i;
ret.Add(i);
}
return ret;
}
public static IEnumerable<int> Primes()
{
_list = new List<int>();
_list.Add(2);
yield return 2;
Func<int, bool> IsPrime = n => _list.TakeWhile(p => p ≤ (int)Math.Sqrt(n)).FirstOrDefault(p => n % p == 0) == 0;
for (int i = 3; i < Int32.MaxValue; i += 2)
{
if (IsPrime(i))
{
_list.Add(i);
yield return i;
}
}
}
public static string Convert(int n)
{
if (n == 0) return ".";
if (n == 1) return "()";
StringBuilder sb = new StringBuilder();
var p = Factor(n);
var max = PrimeOrd(p.Last());
for (int i = 0; i ≤ max; i++)
{
var power = p.FindAll((x) => x == Nth(i)).Count;
sb.Append(Convert(power));
}
return "(" + sb.ToString() + ")";
}
}
class Program
{
static void Main(string[] args)
{
string line = Console.ReadLine();
try
{
int num = int.Parse(line);
Console.WriteLine("{0}: '{1}'", num, P.Convert(num));
}
catch
{
Console.WriteLine("You didn't entered number!");
}
}
}
Il problema è lentezza del procedimento PrimeOrd. Sai qualche soluzione più veloce per scoprire ordine di privilegiata nel numeri primi?
Titolo
se si sa come velocizzare-up ordine di numero primo trovare, per favore, suggerire qualcosa. : -)
Grazie.
P.S. Il più grande primo meno di 2,147,483,648 è 2147483647 ed è 105097565e Prime. Non c'è bisogno di aspettarsi più grande numero di 2 ^ 31.
Soluzione
Si dovrebbe memorizzare nella cache i numeri primi per _List e poi usarlo per entrambi Factor e PrimeOrd. Inoltre evitare di operatori operatori LINQ come TakeWhile che creano valori che si buttano via.
Ecco una versione ottimizzata:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
static class P
{
private static List<int> _list = new List<int>();
public static int Nth(int n)
{
if (_list.Count == 0 || _list.Count <= n)
{
GenerateNextPrimes().First(p => _list.Count >= n);
}
return _list[n];
}
public static int PrimeOrd(int prime)
{
var primes = GrowPrimesTo(prime);
return primes.IndexOf(prime);
}
public static List<int> Factor(int N)
{
List<int> ret = new List<int>();
GrowPrimesTo(N);
for (int ixDivisor = 0; ixDivisor < _list.Count; ixDivisor++)
{
int currentDivisor = _list[ixDivisor];
while (N % currentDivisor == 0)
{
N /= currentDivisor;
ret.Add(currentDivisor);
}
if (N <= 1)
{
break;
}
}
return ret;
}
private static List<int> GrowPrimesTo(int max)
{
if (_list.LastOrDefault() >= max)
{
return _list;
}
GenerateNextPrimes().First(prime => prime >= max);
return _list;
}
private static IEnumerable<int> GenerateNextPrimes()
{
if (_list.Count == 0)
{
_list.Add(2);
yield return 2;
}
Func<int, bool> IsPrime =
n =>
{
// cache upperBound
int upperBound = (int)Math.Sqrt(n);
for (int ixPrime = 0; ixPrime < _list.Count; ixPrime++)
{
int currentDivisor = _list[ixPrime];
if (currentDivisor > upperBound)
{
return true;
}
if ((n % currentDivisor) == 0)
{
return false;
}
}
return true;
};
// Always start on next odd number
int startNum = _list.Count == 1 ? 3 : _list[_list.Count - 1] + 2;
for (int i = startNum; i < Int32.MaxValue; i += 2)
{
if (IsPrime(i))
{
_list.Add(i);
yield return i;
}
}
}
public static string Convert(int n)
{
if (n == 0) return ".";
if (n == 1) return "()";
StringBuilder sb = new StringBuilder();
var p = Factor(n);
var max = PrimeOrd(p.Last());
for (int i = 0; i <= max; i++)
{
var power = p.FindAll(x => x == Nth(i)).Count;
sb.Append(Convert(power));
}
return "(" + sb.ToString() + ")";
}
}
class Program
{
static void Main(string[] args)
{
string line = Console.ReadLine();
int num;
if(int.TryParse(line, out num))
{
Console.WriteLine("{0}: '{1}'", num, P.Convert(num));
}
else
{
Console.WriteLine("You didn't entered number!");
}
}
}
Altri suggerimenti
Questo non è qualcosa che si dovrebbe fare in fase di esecuzione. Una soluzione migliore è quella di pre-calcolare tutti questi numeri primi e poi metterli nel vostro programma in qualche modo (un array statico, o un file da leggere in). Il codice lento viene eseguito come parte del processo di sviluppo (che è lento in ogni caso :-), non in corrispondenza del punto in cui è necessario la vostra velocità.
Poi è solo una questione di una ricerca di qualche tipo, piuttosto che il calcolo ogni volta che ne avete bisogno.
Si prega di vedere così domande:
http://www.google.com /search?q=site%3Astackoverflow.com+prime+number&btnG=Search
Primo numero calcolo divertimento
Come faccio a trovare i numeri primi attraverso le operazioni di bit in C ++?
Se avete bisogno di una lista di numeri primi noti, uno sguardo qui