hi
plz help me how to simple displaying 1 to 20 prime numbers
with for loop
plz help me
If your application type is console then you have to use Console.WriteLine() method. If an app is winform then use UI elements (ListBox).
If your application type is console then you have to use Console.WriteLine() method. If an app is winform then use UI elements (ListBox).
plz if u have any demo code plz post here
i made this demo but i want without Boolean Condition
plz help me
{
int x,y;
bool a = true;
for ( x = 1; x <=20; x++)
{
for ( y = 2; y <= 20; y++)
{
if (x != y && x % y == 0)
{
a = false;
break;
}
}
if (a)
{
Console.WriteLine(x);
}
a = true;
}
Console.Read();
}
Write an IsPrime function.
also on line 6 you don't have to let go the variable y all the way to 20.
The square root of 20 will do.
See :
int x, y;
bool a = true;
int SQRT = (int)Math.Sqrt(20); // SQRT=4
for (x = 1; x <= 20; x++)
{
for (y = 2; y <= SQRT; y++)
{
if (x != y && x % y == 0)
{
a = false;
break;
}
}
if (a)
{
Console.WriteLine(x);
}
a = true;
}
Console.Read();
Using enumerator
using System;
using System.Collections.Generic;
namespace ConsoleApplication1 {
class Program {
static void Main() {
foreach (int p in Primes(2000)) {
Console.WriteLine("{0}", p);
}
Console.ReadLine();
}
static IEnumerable<int> Primes(int limit) {
if (limit > 1) {
yield return 2;
List<int> primes = new List<int>();
int v = 3;
while (v <= limit) {
Boolean prime = true;
foreach (int p in primes) {
if (v % p == 0) {
prime = false;
break;
}
}
if (prime) {
primes.Add(v);
yield return v;
}
v += 2;
}
}
}
}
}
You can speed up generation a bit by adding in the Sqrt stuff:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1 {
class Program {
static void Main() {
foreach (int p in Primes(200000)) {
Console.WriteLine("{0}", p);
}
Console.ReadLine();
}
static IEnumerable<int> Primes(int limit) {
if (limit > 1) {
yield return 2;
List<int> primes = new List<int>();
int v = 3;
while (v <= limit) {
Boolean prime = true;
int sv = (int)Math.Sqrt(v);
for (int i = 0; i < primes.Count && primes[i] <= sv; i++) {
if (v % primes[i] == 0) {
prime = false;
break;
}
}
if (prime) {
primes.Add(v);
yield return v;
}
v += 2;
}
}
}
}
}
But you'll only need that if you are doing really large lists. And if you are doing those, there are better methods of prime generation :)
thanks
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.