Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
So I'm doing the 7th Project Euler problem, and I'm not sure why this code isn't working, it seems to be okay so small numbers, I've tested 1-10 and it's fine, but doesn't return the correct answer at 10001 - returns 104745.
And yes, I know it's inefficient.
private void eulerSeven(int num)
{
// Start the Prime count at 3, with 2 already counted.
int primecount = 1, counter = 3;
//While num of primes counted < the nth prime
while (primecount < num)
{
bool isPrime = true;
//check every number from 2 -> the current number we're checking
for (int i = 2; i < counter; i++)
{
if (counter%i == 0)
{
//if divisible, not a prime
isPrime = false;
break;
}
}
if (isPrime) //If is a prime, increment counter
{ primecount++; }
// Go to next number (only checking odds)
counter += 2;
}
//output nth prime
Console.WriteLine(counter);
}
As stated by #lanorkin, the problem was:
should be counter - 2
but also, I would like to suggest a look at https://codereview.stackexchange.com/questions/124644/project-euler-7-10001st-prime, so this code should do the same, but very very fast (5ms on my machine):
static void Main(string[] args)
{
var stopwatch = Stopwatch.StartNew();
Console.WriteLine(CalculateEulerSeven(10001)); // should be 104745
stopwatch.Stop();
Console.WriteLine("Time to calculate in milliseconds : {0}", stopwatch.ElapsedMilliseconds);
Console.ReadKey();
}
private static int CalculateEulerSeven(int num)
{
int primecount = 1, counter = 3;
while (primecount < num)
{
bool isPrime = IsPrime(counter);
if (isPrime) primecount++;
counter += 2;
}
return counter;
}
static bool IsPrime(int value)
{
if (value < 2) { return false; }
if (value % 2 == 0) { return value == 2; }
if (value % 3 == 0) { return value == 3; }
if (value % 5 == 0) { return value == 5; }
if (value == 7) { return true; }
for (int divisor = 7; divisor * divisor <= value; divisor += 30)
{
if (value % divisor == 0) { return false; }
if (value % (divisor + 4) == 0) { return false; }
if (value % (divisor + 6) == 0) { return false; }
if (value % (divisor + 10) == 0) { return false; }
if (value % (divisor + 12) == 0) { return false; }
if (value % (divisor + 16) == 0) { return false; }
if (value % (divisor + 22) == 0) { return false; }
if (value % (divisor + 24) == 0) { return false; }
}
return true;
}
Related
static void Main(string[] args)
{
if (isPrimeNumber(6))
{
Console.WriteLine("This is prime number");
}
else
{
Console.WriteLine("This is not prime number");
}
Console.ReadLine();
}
private static bool isPrimeNumber(int number)
{
bool result = true;
for (int i = 0; number - 1; i++)
{
if (number % i == 0)
{
result = false;
i = number;
}
}
return result;
}
hey! there is a problem in my code blocks about prime number verifying. this program returns me that in for loop: cannot convert type "int" to "bool". how can i fix it? what's my wrong?
for (int i = 0; number - 1; i++) should be for (int i = 0; i < number; i++) The number - 1 is not a boolean expression.
private static bool isPrimeNumber(int number)
{
bool result = true;
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
result = false;
i = number;
}
}
return result;
}
i fixed it for (int i = 0; i < number; i++) should be for (int i = 2; i < number; i++)
You have logical error, look
//typo: should be i < number - 1 instead of number - 1
for (int i = 0; i < number - 1; i++)
{
if (number % i == 0) // <- always true, when i == 1
{
result = false; // <- result == false whenever number >= 2
i = number;
}
}
whenever i == 1 then number % i == 0 and you have result = false.
Let's implement isPrimeNumber from scratch:
private static bool isPrimeNumber(int number) {
// 0, 1 and negative numbers are not prime
if (number <= 1)
return false;
// we have just one even prime number, it's 2
if (number % 2 == 0)
return number == 2;
// if we have a non-trivial divisors, the minimal one
// is at most Sqrt(number)
// (int) (...+1) - to be on the safe side in case of rounding errors
int maxDivisor = (int)(Math.Sqrt(number) + 1);
// Now we check divisor = 3, 5, 7, ..., maxDivisor
for (int divisor = 3; divisor <= maxDivisor; divisor += 2)
if (number % divisor == 0)
return false;
// All tests passed, number is prime
return true;
}
Do not convert number to other type. Do not use built-in functions like Contains(), StartsWith(), etc.
while (number > 0)
{
if (number % 10 == 3)
{
return true;
}
number /= 10;
}
return false;`
Method that checks if given number (positive integer) contains digit 3
You were nearly there
private static bool HasDigit(int num,int digit)
{
while (num > 0)
{
if(num % 10 == digit)
return true;
num /= 10;
}
return false;
}
Usage
Console.WriteLine(HasDigit(1222, 3));
Console.WriteLine(HasDigit(23345, 3));
Output
False
True
Other approaches might be
private static bool HasDigit2(int num, int digit)
{
var str = num.ToString();
for (int i = 0; i < str.Length; i++)
if (str[i] == ((char) digit) + '0')
return true;
return false;
}
Or
private static bool HasDigit3(int num, int digit)
=> num.ToString().Any(t => t == ((char) digit) + '0');
Here's a recursive solution:
public static bool Contains3(int n) {
if (n < 10) {
if (n == 3) {
return true;
} else {
return false;
}
}
return n % 10 == 3 || Contains3(n / 10);
}
This question already has answers here:
Program to find prime numbers
(28 answers)
Closed 3 years ago.
I am having trouble with a problem that will tell me if a number is prime or not. I am passing every test but the random test. I am an entry level dev so it may not be pretty but I would like help on how to get this to pass a test even if the number is "1008985750798" for example...
public static bool IsPrime(int n)
{
bool returnMe = true;
if (n% 2 == 0 || n % 3 == 0 || n <= 1)
{
returnMe = false;
}
if (n % 2 == 0 && n % 3 == 0)
{
returnMe = false;
}
if ( n == 2 || n == 3 || n == 7)
{
returnMe = true;
While Program to find prime numbers shows a nice, efficient implementation I think you are after something that is easier to understand.
Here's a naive approach:
public static void Main()
{
for(uint i = 0; i < 1000; i++) {
if (IsPrime(i)) Console.Write($"{i},");
}
}
private static bool IsPrime(uint n)
{
if (n < 3) return false;
for (uint i = 2; i < n; i++)
if (n % i == 0) return false;
return true;
}
If you want to go a bit faster, let's ask Wikipedia for help.
/// <summary>
/// Tests the number for primality. It is a c# version of the pseudocode from
/// https://en.wikipedia.org/wiki/Primality_test
/// </summary>
private static bool IsPrime2(uint n)
{
// The following is a simple primality test in pseudocode using
// the simple 6k ± 1 optimization mentioned earlier.
// More sophisticated methods described below are much faster for large n.
if (n <= 3)
return n > 1;
if (n % 2 == 0 || n % 3 == 0)
return false;
uint i = 5;
while (i * i <= n)
{
if (n % i == 0 || n % (i + 2) == 0)
return false;
i = i + 6;
}
return true;
}
Does anyone know if there's a cleaner way of doing this (maybe LINQ)? I want to group the value into bucket, and give it a score, so for example in the code below, if the value is:
less or equal to 5, increase the score by 1
10 and below, increase score by 2
15 and below, increase score by 3
else increase by 4.
There are about 10 properties that I have to do this for, and each property have different range for scoring.
public static PScore GetScore(IEnumerable<PStat> rs)
{
var data = new PScore();
foreach(var item in rs)
{
if(item.Kill <= 5)
{
data.Kills++;
}
else if (item.Kill <= 10)
{
data.Kills += 2;
}
else if (item.Kill <= 15)
{
data.Kills += 3;
}
else
{
data.Kills += 4;
}
}
return data;
}
edit#1
Thanks everyone, the ranges varied as well, and I have 10 properties to loop through, so I use this and just passed in the value and ranges
public static int GetScoreASC(int value, int[] range)
{
if (value <= range[0])
{
return 1;
}
else if (value <= range[1])
{
return 2;
}
else if (value <= range[2])
{
return 3;
}
else if (value <= range[3])
{
return 4;
}
else if (value <= range[4])
{
return 5;
}
else if (value <= range[5])
{
return 6;
}
else if (value <= range[6])
{
return 7;
}
else if (value <= range[7])
{
return 8;
}
else if (value <= range[8])
{
return 9;
}
else
{
return 10;
}
}
This way I can reused the same method for all properties.
I would do some math per each property using LINQ:
public static PScore GetScore(IEnumerable<PStat> rs)
{
var data = new PScore();
data.Kills = rs.Sum(item => Math.Min(item.Kill / 5 + (item.Kill % 5 == 0 ? 0 : 1), 4));
return data;
}
You can repeat yourself less by using Select to grab the Kill values from rs and then Sum to aggregate across them.
public static PScore GetScore(IEnumerable<PStat> rs)
{
return new PScore
{
Kills = rs.Select(item => item.Kill).Sum(kill =>
{
if (kill <= 5) return 1;
if (kill <= 10) return 2;
if (kill <= 15) return 3;
return 4;
})
};
}
If you like Konrad's style of converting the conditionals to a closed form computation, you need to correct his formula slightly. I personally would stick with the conditionals for this, though.
public static PScore GetScore(IEnumerable<PStat> rs)
{
return new PScore
{
Kills = rs.Select(item => item.Kill)
.Sum(kill => Math.Max(1, Math.Min((kill + 4) / 5, 4)));
};
}
I'm trying to find integers in a certain range that are prime. I seem to be getting an error when I put a for loop in my else statement.
private static bool prime(int n,out int factor)
{
factor = 1;
if (n < 2)
return false;
else if (n == 2 || n == 3)
return true;
else if( n % 2 == 0)
return false;
for(int r = 3; r < (Math.Sqrt(n) + 1); r + 2)
{
if ((Convert.ToInt32(n)) % r == 0)
return false;
}
}
for(int r=3;r<(Math.Sqrt(n)+1);r+2)
r+2 creates a result, but it isn't assigned to anything. You want either r = r + 2 or r += 2
There are couple of problems with your code.
Firstly you can fix the assigment problem like
r=r+2
secondly, your function needs to return something from all code paths. Which it isn't doing at the moment. I have returned true at the end, though you can choose your logic here.
private static bool prime(int n, out int factor)
{
factor = 1;
if (n < 2)
return false;
else if (n == 2 || n == 3)
return true;
else if (n % 2 == 0)
{
return false;
}
for (int r = 3; r < (Math.Sqrt(n) + 1); r = r + 2)
{
if ((Convert.ToInt32(n)) % r == 0)
return false;
}
return true;
}