C# - Checking for prime numbers in a limit [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I would like to write a code that shows a list of prime number one number to another number. For example from 1 to 8, it would be 2, 3, 5, 7. I got a code from "Check if number is prime number" by user1954418 because I did not know where to begin, so I take NO credit whatsoever for the code.
int num1;
Console.WriteLine("Prime Number:");
num1 = Convert.ToInt32(Console.ReadLine());
if (num1 == 0 || num1 == 1)
{
Console.WriteLine(num1 + " is not prime number");
Console.ReadLine();
}
else
{
for (int a = 2; a <= num1 / 10; a++)
{
if (num1 % a == 0)
{
Console.WriteLine(num1 + " is not prime number");
return;
}
}
Console.WriteLine(num1 + " is a prime number");
Console.ReadLine();
}

Here is a sample that should work. The code from isPrime I just got from here Here
Then In the main function just have the loop that goes from you starting number to the end number, and runs the isPrime function on each one.
Here is the code:
class Program
{
static void Main(string[] args)
{
int numberStart;
int numberEnd;
// Take in the start point and the end point
Console.WriteLine("Starting Number:");
if(!int.TryParse(Console.ReadLine(), out numberStart)){
Console.WriteLine("Your input is invalid.");
}
Console.WriteLine("Ending Number:");
if (!int.TryParse(Console.ReadLine(), out numberEnd))
{
Console.WriteLine("Your input is invalid.");
}
// Loop from the first number to the last number, and check if each one is prime
for (int number = numberStart; number < numberEnd; number++)
{
Console.WriteLine(number + " is prime?");
Console.WriteLine(isPrime(number) + "\n");
}
Console.ReadLine();
}
// Function for checking if a given number is prime.
public static bool isPrime(int number)
{
int boundary = (int) Math.Floor(Math.Sqrt(number));
if (number == 1) return false;
if (number == 2) return true;
for (int i = 2; i <= boundary; ++i)
{
if (number % i == 0) return false;
}
return true;
}
}
Note that the function isPrime() only checks up to the root, as it is unnecessary to check further as mentioned by the user from the link.
Hope it helps :)

Make it simple; following code will help you:
Console.WriteLine("Enter the Limit:");
int Limit;
if (!int.TryParse(Console.ReadLine(), out Limit))
{
Console.WriteLine("Invalid input");
}
Console.WriteLine("List of prime numbers between 0 and {0} are :",Limit);
for (int i = 2; i < Limit; i++)
{
if (checkForPrime(i))
Console.WriteLine(i);
}
Console.ReadKey();
Where checkForPrime() is defined as follows:
public static bool checkForPrime(int Number)
{
for (int a = 2; a <= Number / 2; a++)
{
if (Number % a == 0)
{
return false;
}
}
return true;
}

Here's some code I wrote/copied to do this in one of my projects. It could probably be a little smoother but it gets the job done.
// Found this awesome code at http://csharphelper.com/blog/2014/08/use-the-sieve-of-eratosthenes-to-find-prime-numbers-in-c/
// This creates a List of Booleans where you can check if a value x is prime by simply doing if(is_prime[x]);
public static bool[] MakeSieve(int max)
{
var sqrt = Math.Sqrt((double)max);
// Make an array indicating whether numbers are prime.
var isPrime = new bool[max + 1];
for (var i = 2; i <= max; i++) isPrime[i] = true;
// Cross out multiples.
for (var i = 2; i <= sqrt; i++)
{
// See if i is prime.
if (!isPrime[i]) continue;
// Knock out multiples of i.
for (var j = i * 2; j <= max; j += i)
isPrime[j] = false;
}
return isPrime;
}
public static List<int> GetListOfPrimes(int max)
{
var isPrime = MakeSieve(max);
return new List<int>(Enumerable.Range(1, max).Where(x => isPrime[x]));
//var returnList = new List<int>();
//for (int i = 0; i <= max; i++) if (isPrime[i]) returnList.Add(i);
//return returnList;
}
Here's an example of usage:
static void Main(string[] args)
{
var x = GetListOfPrimes(8);
foreach (var y in x)
{
Console.WriteLine(y);
}
Console.Read();
}

Related

Problem with prime numbers not printed correctly [duplicate]

This question already has answers here:
Check if number is prime number
(31 answers)
Closed 2 years ago.
I have a problem with my code and i don't know how to solve it. Basically this program prints prime numbers based on the user input and at the end it prints their sum. This works perfectly until a certain amount, example: if i input 10, it shows ten correct prime numbers, but if i input 100, it also prints a number that is not prime, in this case 533. I don't know where i'm wrong.
Thanks for the support.
EDIT: I solved it on my own. Basically there was an error in the first "If" inside the for loop, i've simply added "c = n - 1;" after n++. Now it works perfectly.
Console.Write("How many prime numbers?: ");
int l = Convert.ToInt32(Console.ReadLine());
int n = 2;
int sum = 0;
sum += n;
Console.WriteLine(n);
n++;
int i = 1;
l++;
while (i < l)
{
for (int c = n - 1; c > 1; c--)
{
if (n % c == 0)
{
n++;
}
else if (n % c != 0 && c == 2)
{
sum += n;
Console.WriteLine(n);
n++;
i++;
}
}
}
Console.WriteLine("Sum: " + sum);
Let's start from extracting method:
public static bool IsPrime(int value) {
if (value <= 1)
return false;
if (value % 2 == 0)
retutn value == 2;
int n = (int) (Math.Sqrt(value) + 0.5);
for (int d = 3; d <= n; d += 2)
if (value % d == 0)
return false;
return true;
}
Having this method implemented you can easily compute the sum of the first N primes:
int N = 100;
long s = 0;
for (int p = 1; N > 0; ++p) {
if (IsPrime(p)) {
s += p;
N -= 1;
}
}
Console.Write(s);
Another (a bit more complex) possibility is prime numbers enumeration:
public static IEnumerable<long> Primes() {
yield return 2;
List<int> knownPrimes = new List<int>();
for (int p = 3; ; p += 2) {
int n = (int) (Math.Sqrt(p) = 0.5);
bool isPrime = true;
foreach (int d in knownPrimes) {
if (d > n)
break;
if (p % n == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
knownPrimes.Add(p);
yield return p;
}
}
}
Then you can query enumeration with a help of Linq:
using System.Linq;
...
long s = Primes()
.Take(N)
.Sum();

Is a given number a prime or not, if not output all its divisors

The main part of my code is working, the only thing that doesn't work is the output of all its divisors. My result if it's not a prime should be like this:
Input -> 4
Output -> false 1 2 4
Console.WriteLine("Type your number: ");
int n = Convert.ToInt32(Console.ReadLine());
int a = 0, i;
for (i = 1; i <= n; i++)
{
if (n % i == 0)
{
a++;
}
}
if (a == 2)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false" + i);
}
Console.ReadLine();
To print all the divisors, you'll need to gather them up in a collection of some sort – a list of integers, here.
In addition, all integers are divisible by 1, so you don't want to start there; neither do you want to end at n, since n % n == 0.
var divisors = new List<int>();
for (var i = 2; i < 2; i++)
{
if (n % i == 0)
{
divisors.Add(i);
}
}
if (divisors.Count == 0)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false " + String.Join(" ", divisors));
}
Here is a working solution. You basically have to store your divisors somewhere or print them directly:
public static void Method(int n)
{
if (IsPrime(n))
{
Console.WriteLine($"{n} is a prime");
return;
}
var divisors = new List<int>();
for(var i = 1; i <= n; i++)
{
if (n % i == 0)
divisors.Add(i);
}
Console.WriteLine($"{n} isn't a prime");
Console.WriteLine($"The divisors are: {string.Join(", ", divisors)}");
}
public static bool IsPrime(int n)
{
for(var i = 2; i < n; i++)
{
if (n % i == 0)
return false;
}
return true;
}
From a brief inspection, there are two ways to generate the output. So far, you count the number of divisors, but neither store them nor write them to the output. You could replace
if (n % i == 0)
{
a++;
}
by
if (n % i == 0)
{
Console.WriteLine(i);
a++;
}
or store the divisors in a
List<int>
to generate the output afterwards.

Console.ReadLine() not exiting Program in c#

I have an assignment where I have to create code to display factors and whether a number is a perfect and/or prime number. I think I have all the code right to run my program, but when I get to the last line (Console.ReadLine()) I expect to hit enter and then exit the program. Currently, when I hit enter, the program displays whether it is a prime number and/or perfect number over and over again (each time you hit enter). So basically, it executes everything after the while loop over and over again.
Keep in mind, I'm very new to C#, so some of my syntax and readability may be weird. I am only interested in answers that will help me solve the ReadLine issue. My instructors will help me with making my code more readable and organized.
Thanks for your advice! Here is my code. I commented where the ReadLine isn't closing the program:
using System;
namespace Factorizer.UI
{
class Program
{
static void Main(string[] args)
{
string input;
int num, i, x = 0, sum = 0;
while (true)
{
Console.Write("Enter a number: ");
input = Console.ReadLine();
if (int.TryParse(input, out num))
{
Console.Write("\nThe factors are: ");
for (i = 1; i <= num; i++)
{
if (num % i == 0)
{
Console.Write("{0} ", i);
}
}
break;
}
else
{
Console.WriteLine("\nThat was not a valid number!\n");
}
}
for (i = 1; i < num; i++)
{
if (num % i == 0)
{
sum = sum + i;
}
if (sum == num)
{
Console.Write("\n\n{0} is a perfect number.\n", num);
}
else
{
Console.Write("\n\n{0} is not a perfect number.\n", num);
}
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
x++;
break;
}
}
if (x == 0 && num != 1)
{
Console.Write("\n{0} is a prime number.", num);
}
else
{
Console.Write("\n{0} is not a prime number.", num);
}
Console.ReadLine(); //this isn't closing the program!
}
}
}
}
Console.ReadLine() is inside the for loop. Move it down after the next bracket.
Just put Console.ReadLine(); after the for, it's inside the for block that's why it keeps printing and remove the for that you have after the while block, like this:
string input;
int num, i, x = 0, sum = 0;
while (true)
{
Console.Write("Enter a number: ");
input = Console.ReadLine();
if (int.TryParse(input, out num))
{
Console.Write("\nThe factors are: ");
for (i = 1; i <= num; i++)
{
if (num % i == 0)
{
Console.Write("{0} ", i);
}
}
break;
}
else
{
Console.WriteLine("\nThat was not a valid number!\n");
}
}
/*for (i = 1; i < num; i++)
{*/
if (num % i == 0)
{
sum = sum + i;
}
if (sum == num)
{
Console.Write("\n\n{0} is a perfect number.\n", num);
}
else
{
Console.Write("\n\n{0} is not a perfect number.\n", num);
}
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
x++;
break;
}
}
if (x == 0 && num != 1)
{
Console.Write("\n{0} is a prime number.", num);
}
else
{
Console.Write("\n{0} is not a prime number.", num);
}
Console.ReadLine(); //this isn't closing the program!
//}

Print the prime numbers from 0 to 10,000

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();
}
}
}

c# program for finding if number is prime

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;
}
}

Categories