My problem is the following:
I want to find a prime number less than N
, which corresponding number in 2 base system contains the maximum amount of ones.
For example for N = 87
my program returned 31
(11111 in 2 base system).
I am looking for the better solution to solve this problem.
My algorithm looks like this:
static int Slow(int N)
{
int maxCount = 0;
int maxi = 5;
for (int i = 5; i <= N; i+=2)
{
if (Isprime(i))
{
string x = ConvertToPBase(i, 2);
int count = Count1In(x);
if (count > maxCount)
{
maxCount = count;
maxi = i;
}
}
}
return maxi;
}
my IsPrime
method is the following:
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;
}
My ConvertToPBase
method is the following:
static string ConvertToPBase(int numberInTenBase, int P)
{
List<int> list = new List<int>();
while (numberInTenBase > 0)
{
list.Add((numberInTenBase % P));
numberInTenBase /= P;
}
list.Reverse();
string x = "";
foreach (var item in list)
{
x += item;
}
return x;
}
My Count1In method looks like this:
static int Count1In(string x)
{
int count = 0;
for (int i = 0; i < x.Length; i++)
{
if (Convert.ToInt32(x[i].ToString()) == 1)
count++;
}
return count;
}