Din*_*lla 3 c# optimization performance primes prime-factoring
有简单的密码将数字翻译成系列 . ( )
为了加密这个表示的数字(0 ... 2147483647),我(我想)我需要:
0 . 6 (()())
1 () 7 (...())
2 (()) 8 ((.()))
3 (.()) 9 (.(()))
4 ((())) 10 (().())
5 (..()) 11 (....())
227 (................................................())
2147483648 ((..........()))
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!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是程序PrimeOrd的SLOWNESS.你知道一些更快速的解决方案来找出素数的素数顺序吗?
PS小于2,147,483,648的最大素数是2,147,483,647,它是105,097,565的素数.没有必要期望大于2 ^ 31的数字.
这不是你应该在运行时做的事情.更好的选择是预先计算所有这些素数,然后以某种方式将它们放入程序中(静态数组或要读入的文件).慢速代码然后作为开发过程的一部分运行(无论如何都很慢:-),而不是在你需要速度的时候.
然后,只需要查找某种类型而不是每次需要时计算它们.
| 归档时间: |
|
| 查看次数: |
2041 次 |
| 最近记录: |