i've write this piece of code to check if a number is prime or not, but it doesen't work, I mean that the output is:
1 isn't a prime number
2 is a prime number
3 isn't a prime number
4 is a prime number etc.
please can you tell me what are my mistakes,
thanks
p.s. i've writenumber =1 because i can't divide a number for 0.
for( int number =1;number <101 && number >0;number++)
{
int reimander = (number / 1) & (number / number);
Console.WriteLine(number +(reimander == 0 ? " is a prime number" : " isn't a prime number"));
}
As mentioned Daisy Shipton, your checkings are not sufficient to determine if your number is prime.
In order for a number to be prime, it has to be only divisible by one or itself.
That mean you should check the division by every single numbers between 3 and the number which you are checking the fact of behing prime.
In reality, you don't need to check every numbers between 3 and your number but only the ones between 3 and the square of your number.
In fact, if a whole number k is composite (non prime), it can be written as the product of two whole numbers p and q : k = p*q
Howevern those two numbers p and q can't be simultaneously greater than the square (s) of k, because in this case, their product whould be greater than k.
if p > s and q > s, then p x q > s x s, that to say p x q > k.
The code should looks like something like that (not tested) :
public static bool IsPrime(int number)
{
/****** easy check before going to long calculations *******/
if (number < 2) return false; // A prime number is always greater than 1
if (number == 2) return true; // 2 is prime
if (number % 2 == 0) return false; // Even numbers except 2 are not prime
/****** if your number is Odd and not equals to 2,
you have to check every numbers between 3
and the square of your number *******/
var boundary = (int)Math.Floor(Math.Sqrt(number)); // square of your number
// increment i by 2 because you already checked that your number is Odd
// and therefore not divisible by an Even number
for (int i = 3; i <= boundary; i += 2)
{
if (number % i == 0) return false; // the number can be devided by an other => COMPOSITE number
}
return true; // number at least equals to 3, divisible only by one or itself => PRIME number
}
Now you could do a basic loop for each numbers you want to test and call this function of them. Their is a lot of methods to calculate a series of prime numbers but their are also much more complicated to understand.
for (int number = 1; number < 101 && number > 0; number++)
{
Console.WriteLine(number + " is " + (IsPrime(number) ? "prime" : "not prime"));
}
There are two sorts of problem here: the is-prime algorithm and the C# syntax.
To understand the algorithm for whether a number is prime, search math sites online. For example, here.
Once you know how the math works, you can convert it into code. Based on the code you already have, you should learn the difference between & and && and how to get a remainder.
Related
I know to change the value in nested for loop i=2 the program will not give result in prime numbers. But I want to know the reason and purpose of assigning only 2 to i. Also a Plus if someone explain this using pseudo code.
using System;
namespace Prime_number
{
class Program
{
static void Main(string[] args)
{
int num, i, count, start, end;
Console.Write("Enter Start of range: ");
start = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter End of range : ");
end = Convert.ToInt32(Console.ReadLine());
Console.Write("The prime numbers between {0} and {1} are : \n", start, end);
for (num = start; num <= end; num++)
{
count = 0;
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
count++;
break;
}
}
if (count == 0 && num != 1)
Console.Write(num + "\n");
}
Console.Write("\n");
}
}
}
It is a self explanatory code:
Read the range_start value.
Read the range_end value.
For each value from range_start to range_end
Check if valueis divisible by any number in range 2 to the half of value
It will be prime if it is not divisible.
The divisors 0 and 1 are not tested for obvious reasons, all numbers are divisible by 1 and any number divided by 0 gives same result, infinity, in limits theory, or divide by zero exception, in a real CPU implementation. only numbers up to value / 2 are tested for an also obvious reason, value would not be divisible by any number in that range but itself.
EDIT: As you're working with integer values, one small optimization would be to use value >> 1 instead of value / 2, shift operations are way faster than div operations at CPU level, yet compilers often apply this optimization when the divisor is known at compile-time.
Homework alert! I am trying to build a console app to determine whether a given integer is an Armstrong number. I found a working solution online, but after spending far too much time analyzing it, I still don't understand the logic well enough to reproduce it on my own... The two pain points I've identified are 1) I do not understand exactly how the Parse method is acting upon the integer that the user inputs, and 2) the logic sequence of the for loop is not self-evident (see code and my logic description below):
int number, remainder, sum = 0;
Console.WriteLine("Enter a number: ");
number = int.Parse(Console.ReadLine());
for (int i = number; i > 0; i = i / 10)
{
remainder = i % 10;
sum = sum + remainder * remainder * remainder;
}
if (sum == number)
{
Console.Write("Entered Number is an Armstrong Number");
}
else
Console.Write("Entered Number is not an Armstrong Number");
Console.ReadLine();
This is how my understanding of the for loop logic breaks down:
The integer is passed into the for loop and assigned to int i
//e.g. i = 153//
If the value of i is greater than 0, then re-assign the value of i to i/10 //e.g. 153/10 == 15r3 //
Assign the remainder value of i/10 to int remainder //e.g. remainder = 3//
Compute the sum as sum + remainder * remainder * remainder //e.g. sum = 0 + 3 * 3 * 3//
if the sum is equal to the number, then print "Entered number is Armstrong number" //e.g. however, 27 !== 153//
What am I missing here?
Since this is self-admitted homework, I'm not going to give you a complete answer, but pointers instead.
Make number a string variable. You can then use your for loop to go through each character in the string and perform the math on them.
Use math.pow to create your sum, not sum = sum + remainder * remainder * remainder, since this makes the assumption that you are always using a 3-digit number. (hint: int N = number.Length()
Helper links:
math.pow
Armstrong Numbers
The problem I am trying to solve is to find the primality of an arbitrarily long number (BigInteger) in C#. To achieve this task, I have implemented the "Sieve of Erathostenes". The algorithm is already fast, but in terms of accuracy, I am skeptical as I am unsure of how accurate BigInteger is in representing arbitrarily long numbers.
The "Sieve of Erathostenes" algorithm
public static bool IsPrime(BigInteger value)
{
int result = 0;
// 2, 3, 5 and 7 are the base primes used in the Sieve of Erathostenes
foreach (int prime in new int[] { 2, 3, 5, 7 })
{
// If the value is the base prime, it's prime - no further calculation required.
if (value == prime)
{
return true;
}
// Else, we need to work out if the value is divisible, by any of these primes...
BigInteger remainder = 0;
BigInteger.DivRem(value, prime, out remainder);
if (remainder != 0)
{
// We increment result to indicate that the value was not divisible by the base prime
result++;
}
}
// If result is 4, thus, not divisible my any of the base primes, it must be prime.
return result == 4;
}
My question is not "why is my code not working" - it's more "is this accurately determining primality of BigInteger"
Specifically, I would like to know about the accuracy of BigInteger.DivRem
Sieve of Erathostenes is work as follow:
First assume that all numbers is prime.
Starting from 2, crossing out all the numbers that is a multiple of two. Then, move to the next number that is not crossed out, and remove all multiple of this number, and so on... so, in the end what is left is the list of prime number.
So clearly, your code is not Sieve of Erathostenes, which you made an assumption that the list of prime is only 2,3,5,7
To check whether a number is a prime or not, we can have a more easy way, instead of using Sieve of Erathostenes, which is only suitable when you want to generate a list of prime numbers.
Pseudo Code:
boolean isPrime(int num){
for(int i = 2; i*i <= num ; i++){
if(num % i == 0){
return false;
}
}
return true;
}
This question already has answers here:
Program to find prime numbers
(28 answers)
Closed 6 years ago.
This particular question does not involve loops and most of the answers I have seen involve loops. This is a challenge from one of the books I am reading. No, I'm not a student (38 years old) I'm actually switching careers, so I've decided to start learning how to program. The book I am reading is called "Introduction to C# / Joes 2 Pros".
Here's the code I have so far. I know there is more than likely a better way to do this using things I probably don't have a good grasp on. For example, I know what a "bool" is, but just haven't used it in any of my coding yet. Therefore, it's difficult to implement it.
int myChoice;
Console.Write("Please enter a number: ");
myChoice = int.Parse(Console.ReadLine());
if (myChoice >= 1 && myChoice % myChoice == 0)
{
Console.WriteLine("That's correct, {0} is a prime number.", myChoice);
}
else
{
Console.WriteLine("That is not a prime number.");
}
Console.ReadLine();
OK, as you can see the program asks for the user to enter a number. As determined by the if statement, if the number is greater than or equal to 1 AND the number is divisible by itself with no remainder, the statement is true.
I know there is a much better way of finding out if the number entered is a prime, but I just can't figure out what it is. The program does what I expect it to do except figuring out if the number is prime.
Just a bit of background here. What you are seeing on the screen is just about the extent of my knowledge of C#. Beyond what you see, I'm probably lost.
Any suggestions?
There is another very challenging requirement to test for prime, it must not divide by any other numbers. For example 4 is greater than zero and 4 % 4 = 0. But 4 is not a prime, it is equal to 2x2.
Testing for prime is rather difficult. Most starting programming books want you to experiment with the Sieve of Eratosthenes, which is an old way to determine if a number is a prime. The wiki page proposes an algorithm to implement for this. Basically you generate numbers from 1 to 100 in an array and remove those who are not prime, leaving you all primes from 1 to 100.
If your number n is small, it is simple to test all numbers less than sqrt(n) as divisors; if none of them divide n, then n is prime:
function isPrime(n)
d := 2
while d * d <= n
if n % d == 0
return Composite
d := d + 1
return Prime
For larger numbers, a reasonable test of primality is the Miller-Rabin test; it can be fooled (falsely proclaim that a composite number is prime) but with very low likelihood. Start with a strong pseudoprime test:
function isStrongPseudoprime(n, a)
d := n - 1; s := 0
while d is even
d := d / 2; s := s + 1
t := powerMod(a, d, n)
if t == 1 return ProbablyPrime
while s > 0
if t == n - 1
return ProbablyPrime
t := (t * t) % n
s := s - 1
return DefinitelyComposite
Each a for which the function returns ProbablyPrime is a witness to the primality of n; test enough of them and you gain some confidence that n is actually prime:
function isPrime(n)
for i from 1 to k
a := randint(2 .. n-1)
if isStrongPseudoprime(n, a) == DefinitelyComposite
return DefinitelyComposite
return ProbablyPrime
Variable k is the number of trials you want to perform; somewhere between 10 and 25 is typically a reasonable value. The powerMod(b,e,m) function returns b ^ e (mod m). If your language doesn't provide that function, you can efficiently calculate it like this:
function powerMod(b, e, m)
x := 1
while e > 0
if e % 2 == 1
x := (b * x) % m
b := (b * b) % m
e := floor(e / 2)
return x
If you're interested in the math behind this test, I modestly recommend the essay Programming with Prime Numbers at my blog.
Given n natural number starts from 0, and b which is a number in between 0 to n
I wish to randomly select a number excluding b.
Say n is 5
then The number to be selected is {0,1,2,3,4,5}
say b is 4,
then my random selection is from {0,1,2,3,5}
A way to do this is to do a while loop, until the random.nextInteger() does not find a 4.
Is there a easy to to do this other than using a while loop?
I would write a simple extension:
// N.B. : min is inclusive, max is exclusive; so range is: [min,max) - {toExclude}
public static int Next(this Random rand, int min, int max, int toExclude)
{
int v = rand.Next(min, max - 1);
if (v < toExclude)
return v;
return v + 1;
}
Usage:
var random = new Random();
var val = random.Next(0,6,4); // 6 because max is exclusive in C# random.Next()
Your approach is the best in my optinion. It is simple and elegant, and even for m=2 it is O(1) on average (The expected number of redraws is 1/2 + 1/4 + 1/8 + .... < 1).
If you want to avoid the worst case of infinite loop there is an alternative, though I doubt it will have real performance impact.
draw a random double in range [0,1]. let it be d. If d < b/m: draw a number in range [0,b) and return it.
Else (d > b/m) - draw a random number in range [b+1,m] and return it.
Note, it is indeed uniform distributed because:
There are m+1 numbers in range 0,...,m, but only m "valid" numbers (excluding b).
There are b numbers in range 0,1,...,b-1 - so the probability of the number being in this range assuming uniform distribution is b/m - which is exactly P(d < b/m).
In java it will look similar to this:
int m = 5, b = 4;
Random r = new Random();
double d = r.nextDouble();
if (d < ((double)b)/m) {
System.out.println(r.nextInt(b));
} else {
System.out.println(r.nextInt(m-b) + b + 1);
}
Here is another approach if you prefer:
import random
def random_unifrom(n,b):
assert b < n and n > 0 and b > 0
nMinusOneList = [i for i in range(n) if i != b]
lSize = len(nMinusOneList)
randIndex = random.randint(0, lSize-1)
return nMinusOneList[randIndex]
I wrote this in python just for simplicity.
creating the nMinusOneList has complexity of O(n).
returning the random index complexity depends on the random function you are using.
At the end, you loose nothing if you take this approach instead of a while loop, but even if you use the while loop approach, if the random function is random (!!) then you should not have a problem. However, my approach above excludes the number you do not need from the very beginning.
In C#, the one line I use in python might be a couple of lines which consists of a for loop on the range 0 to n, with a condition that the x (for loop index) does not equal to b, in building the list, and then you will have the list that excludes b.