I want to Find prime numbers in interval [1000,9999] where the sum of first and second digits is equal to sum of third and fourth digits of the number.
For example 3517 is prime number and 3 + 5 = 1 + 7
My solution is the following:
for (int i = 1001; i <= 9999; i += 2)
{
if (NumberOfDivisorsOf(i) == 2)
{
string x = i.ToString();
int n1 = Convert.ToInt32(x[0]);
int n2 = Convert.ToInt32(x[1]);
int n3 = Convert.ToInt32(x[2]);
int n4 = Convert.ToInt32(x[3]);
if ((n1 + n2) == (n3 + n4))
Console.WriteLine(i);
}
}
NumberOfDivisorsOf method looks like this:
static int NumberOfDivisorsOf(int a)
{
int count = 2;
int i = 2;
for (; i < a/i ; i++)
{
if (a / i * i == a)
count += 2;
}
if (i * i == a)
count++;
return count;
}
I think NumberOfDivisorsOf method is fine and improvement needs to the solution itself.
I don't want to use LINQ. I want to get them with simple steps..
EDIT:
Depending On OMG answer I improve code as shown below:
for (int i = 1001; i <= 9999; i += 2)
{
if (Isprime(i))
{
int n1 = i / 1000;
int n2 = (i % 1000) / 100;
int n3 = (i % 100) / 10;
int n4 = i % 10;
if ((n1 + n2) == (n3 + n4))
{
Console.WriteLine(i);
}
}
}
I changed NumberOfDivisorOf method to IsPrime method:
static bool Isprime(int n)
{
if (n == 2)
return true;
if (n == 3)
return true;
if ((n % 2) == 0)
return false;
if (n % 3 == 0)
return false;
int i = 5;
int w = 2;
while (i * i <= n)
{
if (n % i == 0)
return false;
i += w;
w = 6 - w;
}
return true;
}
EDIT:
Depending on Siye answer I changed my code as shown below (it made executions speed 3x faster)
for (int i = 1001; i <= 9999; i += 2)
{
int n1 = i / 1000;
int n2 = (i % 1000) / 100;
int n3 = (i % 100) / 10;
int n4 = i % 10;
if ((n1 + n2) == (n3 + n4))
{
if (Isprime(i))
{
Console.WriteLine(i);
}
}
}