Print the prime numbers from 0 to 10,000 - c#

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

Related

Write a program that reads N and then continuously read integers and check if there are odd or even until odd and even number equals N

This is what I tried:
using System;
namespace OddAndEvenNumbers
{
class Program
{
static void Main(string[] args)
{
int requiredOddAndEvenNumbers = Convert.ToInt32(Console.ReadLine());
int oddNumbersCount = 0;
int evenNumbersCount = 0;
int n = Convert.ToInt32(Console.ReadLine());
while (oddNumbersCount <= requiredOddAndEvenNumbers || evenNumbersCount <= requiredOddAndEvenNumbers)
{
if (n % 2 == 0)
{
evenNumbersCount++;
}
else if (n % 2 != 0)
{
oddNumbersCount++;
}
}
Console.WriteLine(evenNumbersCount + " " + oddNumbersCount);
Console.ReadLine();
}
}
}
I don't know why it doesn't work.
The program should stop when odd numbers and even number equals N.
You never update n so the loop will never exit
So evenNumbersCount and oddNumbersCount will never count up
using System;
namespace OddAndEvenNumbers
{
class Program
{
static void Main(string[] args)
{
int requiredOddAndEvenNumbers = Convert.ToInt32(Console.ReadLine());
int oddNumbersCount = 0;
int evenNumbersCount = 0;
int n = Convert.ToInt32(Console.ReadLine());
while (oddNumbersCount <= requiredOddAndEvenNumbers || evenNumbersCount <= requiredOddAndEvenNumbers)
{
if (n % 2 == 0)
{
evenNumbersCount++;
}
else if (n % 2 != 0)
{
oddNumbersCount++;
}
n++;
}
Console.WriteLine(evenNumbersCount + " " + oddNumbersCount);
Console.ReadLine();
}
}
}
It seems you've forgotten to get new number inside the loop. It keeps checking the first number
ItThe while loop works until the Odd + Even numbers are equal to n.
int requiredOddAndEvenNumbers = Convert.ToInt32(Console.ReadLine());
int oddNumbersCount = 0;
int evenNumbersCount = 0;
int n = 0;
while ((oddNumbersCount + evenNumbersCount) < requiredOddAndEvenNumbers)
{
n = Convert.ToInt32(Console.ReadLine());
if (n % 2 == 0)
{
evenNumbersCount++;
}
else if (n % 2 != 0)
{
oddNumbersCount++;
}
}
Console.WriteLine("evenNumbersCount: {0}", evenNumbersCount);
Console.WriteLine("oddNumbersCount: {0}", oddNumbersCount);

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.

A recursion related issue in c#

This is the background to this question:
Background
Take any integer n greater than 1 and apply the following algorithm
If n is odd then n = n × 3 + 1 else n = n / 2
If n is equal to 1 then stop, otherwise go to step 1
The following demonstrates what happens when using a starting n of 6
6 - 3 - 10 - 5 - 16 - 8 - 4 - 2 - 1
After 8 generations of the algorithm we get to 1.
It is conjectured that for every number greater than 1 the repeated application of this algorithm will
eventually get to 1.
The question is how can I find a number that takes exactly 500 generations to reduce to 1?
The code below is my version but appearntly got some wrong logic. Could you help me correct this? Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sequence1
{
class Program
{
static void Main(string[] args)
{
int start = 1;
int flag = 0;
int value;
while(true){
int temp = (start - 1) / 3;
string sta = temp.ToString();
if (Int32.TryParse(sta, out value) )
{
if (((start - 1) / 3) % 2 == 1)
{
start = (start - 1) / 3;
flag++;
if (flag == 500)
{
break;
}
}
else
{
start = start * 2;
flag++;
if (flag == 500)
{
break;
}
}
}
else
{
start = start * 2;
flag++;
if (flag == 500)
{
break;
}
}
}
Console.WriteLine("result is {0}", start);
Console.ReadLine();
}
}
}
Since your question's title is "A recursion related issue", I will give you a recursive solution.
int Process(int input, int maxRecursionDepth)
{
// condition to break recursion
if (maxRecursionDepth == 0 || input == 1)
return input;
if (input % 2 == 1) // odd case
return Process(input * 3 + 1, maxRecursionDepth - 1);
else // even case
return Process(input / 2, maxRecursionDepth - 1);
}
Now to find all number in a specified range, that return 1 after exactly 500 recursions:
int startRange = 1, endRange = 1000;
int maxDepth = 500;
List<int> resultList = new List<int>();
for (int i = startRange; i <= endRange; i++)
{
if (Process(i, maxDepth) == 1)
resultList.Add(i);
}
Your problem is a part of Collatz conjecture (about recursively defined function) which has not been solved yet:
http://en.wikipedia.org/wiki/Collatz_conjecture
so I think brute force is a good way out:
public static int GetMinNumber(int generations) {
if (generations < 0)
throw new ArgumentOutOfRangeException("generations");
// Memoization will be quite good here
// but since it takes about 1 second (on my computer) to solve the problem
// and it's a throwaway code (all you need is a number "1979515")
// I haven't done the memoization
for (int result = 1; ; ++result) {
int n = result;
int itterations = 0;
while (n != 1) {
n = (n % 2) == 0 ? n / 2 : 3 * n + 1;
itterations += 1;
if (itterations > generations)
break;
}
if (itterations == generations)
return result;
}
}
...
int test1 = GetMinNumber(8); // <- 6
int test2 = GetMinNumber(500); // <- 1979515
Observing the problem,
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
In the third iteration we hit the number 10, which is smaller than 13
So instead of calculating the sequence count every time we can use a cache.
static int GetMinCollatz(int maxChain)
{
const long number = 1000000;
int minNumber = 0;
// Temporary values
int tempCount = 0;
long temp = 0;
// Cache
int[] sequenceCache = new int[number + 1];
// Fill the array with -1
for (int index = 0; index < sequenceCache.Length; index++)
{
sequenceCache[index] = -1;
}
sequenceCache[1] = 1;
for (int index = 2; index <= number; index++)
{
tempCount = 0;
temp = index;
// If the number is repeated then we can find
// sequence count from cache
while (temp != 1 && temp >= index)
{
if (temp % 2 == 0)
temp = temp / 2;
else
temp = temp * 3 + 1;
tempCount++;
}
sequenceCache[index] = tempCount + sequenceCache[temp];
if (sequenceCache[index] == maxChain)
{
minNumber = index;
}
}
return minNumber;
}
For more details refer project euler and this.
A recursive solution
private void ReduceTo1(int input, ref int totalCount)
{
totalCount++;
if (input % 2 == 0)
{
input = input / 2;
}
else
{
input = input * 3 + 1;
}
if (input != 1)
ReduceTo1(input, ref totalCount);
}
to test
int desireValue = 0;
for (int i = 1; i < 100000; i++)
{
int totalCount = 0;
ReduceTo1(i, ref totalCount);
if (totalCount >= 500)
{
desireValue = i;
break;
}
}

Input an Integer and get its prime factors and duplicates [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Prime Factors In C#
I am trying to get this coding to give me all the prime factors of the integer that is inputted, including its duplicates. I have this current code and it seems to be working sort of but it isn't showing all of it's prime factors and duplicates. Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _1_Numeric_Problem
{
class Program
{
static void Main(string[] args)
{
string myInput;
int myInt;
int p;
Console.WriteLine(("Please input an integer"));
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
{
for (int i = 2; i > 1; i++)
{
if (i == 100000)
break;
if (myInt % i == 0)
{
if (i <= 3)
{
Console.Write("{0} ", i);
Console.ReadLine();
continue;
}
else
{
for (p = 2; p < i; p++)
if (i % p != 0)
{
Console.Write("{0} ", i);
Console.ReadLine();
return;
Console.ReadLine();
}
else
{
p++;
continue;
}
}
}
}
}
}
}
}
Try replacing the following code:
for (p = 2; p < i; p++) {
if (i % p != 0) {
Console.Write("{0} ", i);
Console.ReadLine();
return;
Console.ReadLine();
} else {
p++;
continue;
}
}
With this instead:
bool isPrime = true;
for (p = 2; p <= Math.Sqrt(i); p++) {
if (i % p == 0) {
isPrime = false;
break;
}
if (isPrime) {
Console.Write("{0} ", i);
Console.ReadLine();
}
}
Can't you just make a for loop like this?
for (int i = 2; i < myInt; i++)
{
if(myInt % i == 0)
//Do something with it.
}
The basic algorithm for integer factorization using trial division tries each potential factor starting from 2, and if it divides n, outputs the factor, reduces n, and searches for the next factor; note that f is not incremented if it divides n, since it might again divide the reduced n. The loop stops when f is greater than the square root of n, since at that point n must be prime. Here's the pseudocode:
function factors(n)
f := 2
while f * f <= n
if n % f == 0
output f
n := n / f
else
f := f + 1
output n
There are better ways to factor integers, but that should get you started. When you're ready for more, I modestly recommend this essay on my blog.

Categories