I am trying to find the next prime number after the number the user enters in.
Here is the code I have so far:
public int Calculation(int number)
{
//set the isPrime to false
bool isPrime = false;
//do this while isPrime is still false
do
{
//increment the number by 1 each time
number = number + 1;
int squaredNumber = (int)Math.Sqrt(number);
//start at 2 and increment by 1 until it gets to the squared number
for (int i = 2; i <= squaredNumber; i++)
{
//how do I check all i's?
if (number % i != 0)
{
isPrime = true;
}
}
} while (isPrime == false);
//return the prime number
return number;
}
I know something is missing because the first time i gives a remainder that is NOT 0 then it returns that number as prime. The problem is I can't figure out the logic/syntax to see if every i in that loop is NOT 0 as remainder.
There are better ways to find prime numbers, but keeping in line with your algorithm, what you want to do is start with isPrime = true;, then set it to false if there are any i where the remainder is 0. You can also break out of the loop at that point.
So a revised version:
public int Calculation(int number)
{
while(true)
{
bool isPrime = true;
//increment the number by 1 each time
number = number + 1;
int squaredNumber = (int)Math.Sqrt(number);
//start at 2 and increment by 1 until it gets to the squared number
for (int i = 2; i <= squaredNumber; i++)
{
//how do I check all i's?
if (number % i == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
return number;
}
}
If you use a BitArray as a Sieve of Eratosthenes you won't need a loop to test for prime. The value of the BitArray at that index will be true or false according to whether it's prime.
A function like this will produce the Bitarray:
public static BitArray ESieve(int upperLimit)
{
int sieveBound = (int)(upperLimit - 1);
int upperSqrt = (int)Math.Sqrt(sieveBound);
BitArray PrimeBits = new BitArray(sieveBound + 1, true);
PrimeBits[0] = false;
PrimeBits[1] = false;
for(int j = 4; j <= sieveBound; j += 2)
{
PrimeBits[j] = false;
}
for(int i = 3; i <= upperSqrt; i += 2)
{
if(PrimeBits[i])
{
int inc = i * 2;
for(int j = i * i; j <= sieveBound; j += inc)
{
PrimeBits[j] = false;
}
}
}
return PrimeBits;
}
Declare the Bitarray:
BitArray IsPrime = ESieve(1000000);
Finding the next prime is a simple matter of iterating through the bitarray to find the next one set to true:
int FindNextPrime(int number)
{
number++;
for(; number < IsPrime.Length; number++)
//found a prime return that number
if(IsPrime[number])
return number;
//no prime return error code
return -1;
}
if ((number % i) != 0)
{
isPrime = true;
}
You need to wrap number % i in parens due to % having lower operator precedence to !=. I didn't test the correctness of the rest of your logic, but an input of 5 correctly returns 7 as the next prime.
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;
}
// CostNextUpgrade[n] simply equals the cost of the next upgrade of upgrade 'n',
// if n == 0, the buymax boolean = true
if (CostNextUpgrade[UpgradeNumber] <= TotalCash) { AbilityToBuyOne = true; }
if (n == 0) { BuyMax = true; }
else { BuyMax = false; }
// Boolean BuyMax simply states true if they have selected option to buy maximum buildings.
// BUYS MAX AMOUNT OF BUILDINGS
while (BuyMax == true)
{
// AbilityToBuyOne is determined above if they have the cash to buy 1 upgrade,
// this should loop until AbilityToBuyOne becomes false.
if (AbilityToBuyOne == true)
{
TotalCash -= CostNextUpgrade[UpgradeNumber]; //Subtracts cost from total cash
NumberOwned[UpgradeNumber] += 1; //Increments # owned
}
}
This code snippet is called when a buy button is pressed. If the player wants to buy the maximum amount of 'n' then buy max is set to true by another function. That works fine. My issue is how Unity gives negative to positive infinity errors when I try to use this loop. If I have the $ to buy a small amount of upgrades (1-50ish) then the code works alright. But over that, an error is thrown about decimal math using infinity.
I think you have your logic all wrong.
You want to loop while the cost of the next upgrade is less than the total cash available AND (BuyMax is true OR NumOfItemsLeftToBuy >= 1)
Take a look at these test methods, this should be able to help you.
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
int[] CostNextUpgrade = new int[5];
int[] NumberOwned = new int[5];
for (int i = 0; i < CostNextUpgrade.Length; i++)
{
CostNextUpgrade[i] = i;
}
// Buy the max number of upgrade number 2 then exit
int n = 0;
bool BuyMax = n == 0; // BuyMax is true if n == 0
int UpgradeNumber = 2;
int TotalCash = 10;
while (CostNextUpgrade[UpgradeNumber] <= TotalCash &&
(BuyMax == true || n >= 1))
{
TotalCash -= CostNextUpgrade[UpgradeNumber];
NumberOwned[UpgradeNumber] += 1;
n--;
}
// Assert we can't afford another upgrade
Assert.IsTrue(TotalCash < CostNextUpgrade[UpgradeNumber]);
}
[TestMethod]
public void TestMethod2()
{
int[] CostNextUpgrade = new int[5];
int[] NumberOwned = new int[5];
for (int i = 0; i < CostNextUpgrade.Length; i++)
{
CostNextUpgrade[i] = i;
}
// Buy 3 of upgrade number 2
int n = 3;
bool BuyMax = n == 0; // BuyMax is true if n == 0
int UpgradeNumber = 2;
int TotalCash = 10;
while (CostNextUpgrade[UpgradeNumber] <= TotalCash &&
(BuyMax == true || n >= 1))
{
TotalCash -= CostNextUpgrade[UpgradeNumber];
NumberOwned[UpgradeNumber] += 1;
n--;
}
// Assert we bought exactly 3
Assert.AreEqual(NumberOwned[UpgradeNumber], 3);
}
}
}
Im currently trying to create a program that prints the prime numbers from 0 to 10,000 using only for,do while and ifs. I created this program but it doesn't runs
static void Main(string[] args)
{
for (int x = 2; x < 10000; x++)
{
for (int y = 1; y < x; y++)
{
if (x % y != 0)
{
Console.WriteLine(x);
}
}
Console.ReadKey();
}
I don't know where the problem is and also if the for inside resets.
Try this with no bool variable!!!:
static void Main(string[] args)
{
for (int x = 2; x < 10000; x++)
{
int isPrime = 0;
for (int y = 1; y < x; y++)
{
if (x % y == 0)
isPrime++;
if(isPrime == 2) break;
}
if(isPrime != 2)
Console.WriteLine(x);
isPrime = 0;
}
Console.ReadKey();
}
Check Console.ReadKey(); it should be after upper for loop, you can even change condition for upper for loot with <= since 10000 also need to check for prime condition.
Below is the efficient way to print prime numbers between 0 and 10000
using System.IO;
using System;
class Program
{
static void Main()
{
Console.WriteLine("Below are prime numbers between 0 and 10000!");
Console.WriteLine(2);
for(int i=3;i<=10000;i++)
{
bool isPrime=true;
for(int j=2;j<=Math.Sqrt(i);j++)
{
if(i%j==0)
{
isPrime=false;
break;
}
}
if(isPrime)
{
Console.WriteLine(i);
}
}
}
}
Is there any reason that you put Console.ReadKey(); inside of loop?
You should put that out of the loop unless press key during loop.
static void Main(string[] args)
{
for (int x = 2; x < 10000; x++)
{
for (int y = 1; y < x; y++)
{
if (x % y != 0)
{
Console.WriteLine(x);
}
}
}
Console.ReadKey();
}
And probably that code is just print lots of x.
You should to fix it.
The first problem is that x % 1 will always be zero, at least for non-zero x. You need to start the test (inner) loop at one and, for efficiency, stop when you've exceeded the square root of the number itself - if n has a factor f where f > sqrt(n), you would have already found the factor n / f.
The second problem is that you will write out a candidate number every time the remainder is non-zero. So, because 15 % 4 is three, it will be output despite the fact that fifteen is very much a non-prime. It will also be output at 15 % 2, 15 % 4, 15 % 6, 15 % 7, and so on.
The normal (naive) algorithm for prime testing is:
# All numbers to test.
foreach number 2..whatever:
# Assume prime, check all numbers up to squareroot(number).
isPrime = true
foreach test 2..infinity until test * test > number:
# If a multiple, flag as composite and stop inner loop.
if number % test == 0:
isPrime = false
exit foreach
end
end
# If never flagged as composite, output as prime.
if isPrime:
output number
end
Here is simple logic to Print Prime No for any upper limit.
Input : 10 Output : 2 , 3 , 5 ,7
namespace PurushLogics
{
class Purush_PrimeNos
{
static void Main()
{
//Prime No Program
bool isPrime = true;
Console.WriteLine("Enter till which number you would like print Prime Nos\n");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("Prime Numbers : ");
for (int i = 2; i <= n; i++)
{
for (int j = 2; j <= n; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
Console.Write("\t" + i);
}
isPrime = true;
}
Console.ReadKey();
}
}
}
Here is my code where you can generate and print the prime numbers between two numbers (in between string_starting_number and string_last_number). The lowest possible value for string_starting_number is 0 and the highest possible value for string_last_number is decimal.MaxValue-1=79228162514264337593543950334 and not 79228162514264337593543950335 because of the decimal_a++ command inside a for loop which will result to an overflow error.
Take note that you should input the values in string type in string_starting_number and in string_last_number.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeneratingPrimeNumbers
{
class Program
{
static void Main(string[] args)
{
string string_starting_number = "1"; //input here your choice of starting number
string string_last_number = "10"; //input here your choice of last number
decimal decimal_starting_number = Convert.ToDecimal(string_starting_number);
decimal decimal_last_number = Convert.ToDecimal(string_last_number);
string primenumbers = "";
ulong ulong_b;
ulong ulong_c;
if (decimal_starting_number <= ulong.MaxValue)
{
ulong ulong_starting_number = Convert.ToUInt64(decimal_starting_number);
ulong ulong_last_number;
if (decimal_last_number > ulong.MaxValue)
{
ulong_last_number = ulong.MaxValue;
}
else
{
ulong_last_number = Convert.ToUInt64(decimal_last_number);
}
if (ulong_starting_number == 0 || ulong_starting_number == 1 || ulong_starting_number == 2 || ulong_starting_number == 3)
{
primenumbers = 2 + " " + 3;
ulong_starting_number = 5;
}
if (ulong_starting_number % 2 == 0)
{
ulong_starting_number++;
}
ulong ulong_a;
for (ulong_a = ulong_starting_number; ulong_a <= ulong_last_number; ulong_a += 2)
{
ulong_b = Convert.ToUInt64(Math.Ceiling(Math.Sqrt(ulong_a)));
for (ulong_c = 3; ulong_c <= ulong_b; ulong_c += 2)
{
if (ulong_a % ulong_c == 0)
{
goto next_value_of_ulong_a;
}
}
primenumbers = primenumbers + " " + ulong_a;
next_value_of_ulong_a:
{
}
}
}
if (decimal_last_number > ulong.MaxValue)
{
string ulong_maximum_value_plus_two = "18446744073709551617";
if (decimal_starting_number <= ulong.MaxValue)
{
decimal_starting_number = Convert.ToDecimal(ulong_maximum_value_plus_two);
}
if (decimal_starting_number % 2 == 0)
{
decimal_starting_number++;
}
decimal decimal_a;
for (decimal_a = decimal_starting_number; decimal_a <= decimal_last_number; decimal_a += 2)
{
ulong_b = Convert.ToUInt64(Math.Ceiling(Math.Sqrt(ulong.MaxValue) * Math.Sqrt(Convert.ToDouble(decimal_a / ulong.MaxValue))));
for (ulong_c = 3; ulong_c <= ulong_b; ulong_c += 2)
{
if (decimal_a % ulong_c == 0)
{
goto next_value_of_decimal_a;
}
}
primenumbers = primenumbers + " " + decimal_a;
next_value_of_decimal_a:
{
}
}
}
Console.WriteLine(primenumbers);
Console.ReadKey();
}
}
}
I have a code here written in C# that finds the smallest multiple by all numbers from 1 to 20. However, I find it very inefficient since the execution took awhile before producing the correct answer. I would like to know what are the different ways that I can do to improve the code. Thank You.
public static void SmallestMultiple()
{
const ushort ARRAY_SIZE = 21;
ushort[] array = new ushort[ARRAY_SIZE];
ushort check = 0;
for (uint value = 1; value < uint.MaxValue; value++)
{
for (ushort j = 1; j < ARRAY_SIZE; j++)
{
array[j] = j;
if (value % array[j] == 0)
{
check++;
}
}
if (check == 20)
{
Console.WriteLine("The value is {0}", value);
}
else
{
check = 0;
}
}
}
static void Main(string[] args)
{
int[] nums = Enumerable.Range(1, 20).ToArray();
int lcm = 1;
for (int i = 0; i < nums.Length; i++)
{
lcm = LCM(lcm, nums[i]);
}
Console.WriteLine("LCM = {0}", lcm);
}
public static int LCM(int value1, int value2)
{
int a = Math.Abs(value1);
int b = Math.Abs(value2);
// perform division first to avoid potential overflow
a = checked((a / GCD(a, b)));
return checked((a * b));
}
public static int GCD(int value1, int value2)
{
int gcd = 1; // Greates Common Divisor
// throw exception if any value=0
if (value1 == 0 || value2 == 0)
{
throw new ArgumentOutOfRangeException();
}
// assign absolute values to local vars
int a = Math.Abs(value1); // local var1
int b = Math.Abs(value2); // local var2
// if numbers are equal return the first
if (a == b) { return a; }
// if var "b" is GCD return "b"
if (a > b && a % b == 0) { return b; }
// if var "a" is GCD return "a"
if (b > a && b % a == 0) { return a; }
// Euclid algorithm to find GCD (a,b):
// estimated maximum iterations:
// 5* (number of dec digits in smallest number)
while (b != 0)
{
gcd = b;
b = a % b;
a = gcd;
}
return gcd;
}
}
Source : Fast Integer Algorithms: Greatest Common Divisor and Least Common Multiple, .NET solution
Since the result must also be divisible by 19 (which is the greatest prime number) up to 20, you might only cycle through multiples of 19.
This should get to to the result about 19 times faster.
Here's the code that does this:
public static void SmallestMultiple()
{
const ushort ARRAY_SIZE = 21;
ushort[] array = new ushort[ARRAY_SIZE];
ushort check = 0;
for (uint value = 19; value < uint.MaxValue; value += 19)
{
for (ushort j = 1; j < ARRAY_SIZE; j++)
{
array[j] = j;
if (value % array[j] == 0)
{
check++;
}
}
if (check == 20)
{
Console.WriteLine("The value is {0}", value);
return;
}
else
{
check = 0;
}
}
}
On my machine, this finds the result 232792560 in a little over 2 seconds.
Update
Also, please note that the initial program did not stop when reaching a solution; I have added a return statement to make it stop.
You're just looking for the LCM of the numbers from 1 to 20:
Where the GCD can be efficiently calculated with the Euclidean algorithm.
I don't know C#, but this Python solution shouldn't be hard to translate:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def lcm(a, b):
return (a * b) / gcd(a, b)
numbers = range(1, 20 + 1)
print reduce(numbers, lcm)
It's pretty fast too:
>>> %timeit reduce(lcm, range(1, 20000))
1 loops, best of 3: 258 ms per loop
EDIT: v2.0 - Major speed improvement
Building on w0lf's solution. A faster solution:
public static void SmallestMultiple()
{
// this is a bit quick and dirty
// (not too difficult to change to generate primeProduct dynamically for any range)
int primeProduct = 2*3*5*7*11*13*17*19;
for (int value = primeProduct; ; value += primeProduct)
{
bool success = true;
for (int j = 11; j < 21; j++)
{
if (value % j != 0)
{
success = false;
break;
}
}
if (success)
{
Console.WriteLine("The value is {0}", value);
break;
}
}
}
You needn't check 1-10 since if something is divisible by x (e.g. 12), it is divisible by x/n (e.g. 12/2 = 6). The smallest multiple will always be a multiple of a product of all the primes involved.
Didn't benchmark C# solution, but equivalent Java solution runs in about 0.0000006 seconds.
Well I'm not sure what exactly you are trying to accomplish here but your out side for loop will run approximately 4,294,967,295 time (uint.MaxValue). So that will take some time...
If you have a way to keep from going to uint.MaxValue - like breaking your loop when you have accomplished what you need to - that will speed it up.
Also, since you are setting array[j] equal to j and then apparently never using the array again why not just do:
value % j
instead of
value % array[j]
Using also code written by W0lf (sorry but i cannot comment on your post) I would improve it (only a little) deleting the array that I think is useless..
public static void SmallestMultiple()
{
const ushort ARRAY_SIZE = 21;
ushort check = 0;
for (uint value = 1; value < uint.MaxValue; value++)
{
for (ushort j = 1; j < ARRAY_SIZE; j++)
{
if (value % j == 0)
{
check++;
}
}
if (check == 20)
{
Console.WriteLine("The value is {0}", value);
}
else
{
check = 0;
}
}
}
I have this task: Write an expression that checks if given positive integer number n (n ≤ 100) is prime. E.g. 37 is prime.
int number = int.Parse(Console.ReadLine());
for (int i = 1; i < 100; i++)
{
bool isPrime = (number % number == 0 && number % i == 0);
if (isPrime)
{
Console.WriteLine("Number {0} is not prime", number);
}
else
{
Console.WriteLine("Number {0} is prime", number);
break;
}
}
This doesn't seem to work. Any suggestioins?
int number = int.Parse(Console.ReadLine());
bool prime = true;
// we only have to count up to and including the square root of a number
int upper = (int)Math.Sqrt(number);
for (int i = 2; i <= upper; i++) {
if ((number % i) == 0) {
prime = false;
break;
}
}
Console.WriteLine("Number {0} is "+ (prime ? "prime" : "not prime"), number);
a. What are you expecting number % number to do?
b. Your isPrime check is "reset" each time through the loop. Something more like this is required:
bool isprime = true;
for(int i = 2; i < number; i++) {
// if number is divisible by i then
// isprime = false;
// break
}
// display result.
The problems are:
the for should start from 2 as any number will be dived by 1.
number % number == 0 - this is all the time true
the number is prime if he meats all the for steps so
else
{
Console.WriteLine("Number {0} is prime", number);
break;
}
shold not be there.
The code should be something like this:
int number = int.Parse(Console.ReadLine());
if (number == 1)
{ Console.WriteLine("Number 1 is prime");return;}
for (int i = 2; i < number / 2 + 1; i++)
{
bool isPrime = (number % i == 0);
if (isPrime)
{
Console.WriteLine("Number {0} is not prime", number);
return;
}
}
Console.WriteLine("Number {0} is prime", number);
please notice that I didn't test this...just wrote it here. But you should get the point.
Semi-serious possible solution with LINQ (need smaller range at least):
var isPrime = !Enumerable.Range(2, number/2).Where(i => number % i == 0).Any();
The Program checks the given number is prime number or not.
A prime number is a number that can only be divided by 1 and itself
class Program
{
bool CheckIsPrimeNumber(int primeNum)
{
bool isPrime = false;
for (int i = 2; i <= primeNum / 2; i++)
{
if (primeNum % i == 0)
{
return isPrime;
}
}
return !isPrime;
}
public static void Main(string[] args)
{
Program obj = new Program();
Console.Write("Enter the number to check prime : ");
int mPrimeNum = int.Parse(Console.ReadLine());
if (obj.CheckIsPrimeNumber(mPrimeNum) == true)
{
Console.WriteLine("\nThe " + mPrimeNum + " is a Prime Number");
}
else
{
Console.WriteLine("\nThe " + mPrimeNum + " is Not a Prime Number");
}
Console.ReadKey();
}
}
Thanks!!!
Here is for you:
void prime_num(long num)
{
bool isPrime = true;
for (int i = 0; i <= num; i++)
{
for (int j = 2; j <= num; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
Console.WriteLine ( "Prime:" + i );
}
isPrime = true;
}
}