I have a problem I've been working on where I want to identify all integers within a given string that are prime (numbers that are divisible only by 1 and itself).
The logic I have written for this problem is done and correct, but in debugging and testing the code I came upon an interesting scenario.
Say I have the following string
This 15 i2s the45best str7ng 1n th3 w0r17ld
Now when the above string was ran through my program it determined that the prime numbers in the string were 5, 2, 5, 7, 3, 7
, which is correct. However, what if I wanted my program to check to see if 15
was prime instead of individually checking if 1
is a prime and then checking to see if 5
is a prime, or if I want to check the primality of 45
instead of 4
and 5
individually?
I'd like to also extend this question to numbers that are, in general, greater than 1 digit long.
Below is the code I have for accomplishing what I've described:
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;
}