【发布时间】:2017-11-12 18:52:32
【问题描述】:
我一直在处理一个问题,我想识别给定字符串中的所有素数整数(只能被 1 和自身整除的数字)。
我为这个问题编写的逻辑已经完成并且是正确的,但是在调试和测试代码时我遇到了一个有趣的场景。
假设我有以下字符串
This 15 i2s the45best str7ng 1n th3 w0r17ld
现在当上面的字符串通过我的程序运行时,它确定字符串中的素数是5, 2, 5, 7, 3, 7,这是正确的。但是,如果我希望我的程序检查15 是否为素数,而不是单独检查1 是否为素数,然后检查5 是否为素数,或者我想检查素数怎么办? 45 而不是 4 和 5?
我还想将此问题扩展到一般长度大于 1 位的数字。
以下是完成我所描述的代码:
private static void Main(string[] args)
{
string sentence = "This 15 i2s the45best str7ng 1n th3 w0r17ld";
string primes = string.Empty;
foreach(char c in sentence)
{
if (char.IsDigit(c))
{
if (isPrime(c - 48))
{
primes += c;
}
}
}
Console.WriteLine(primes.Length > 0 ? $"The prime numbers in\n\n\t{sentence}\n\nare {string.Join<char>(", ", primes)}" : $"There exist no primes in\n\n\t{sentence}");
Console.ReadLine();
}
private static bool isPrime(int number)
{
if(number == 3 || number == 2)
{
return true;
}
if(number % 2 == 0)
{
return false;
}
for(int i = 3; i < (int)Math.Sqrt(number); i++)
{
if(number % i == 0)
{
return false;
}
}
return true;
}
【问题讨论】:
-
显然,您必须编写一些将数字序列视为数字的代码。