1,105,644 Community Members

Displaying Prime Number

Member Avatar
panpwintlay
Newbie Poster
1 post since Sep 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-1
 

Hello friends

As I am a beginner of C# in .NET , I got stuck in this program
This program is about displaying prime numbers between the range of o and the number you entered.
Its running properly.But the output is not correct.

Here is my coding

using System;
using System.Collections.Generic;
using System.Text;

namespace prime
{
    class Program
    {
        static void Main(string[] args)
        {
            int num;
            int result;
            int i, j;

            Console.WriteLine("Untill what number u want to show prime number?");
            num = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("The prime number between o and ur number are:");
            if (num == 2)
                Console.WriteLine("2");

            else
            {

                Console.WriteLine("2");
                for (i = 3; i <= num; i++)
                {
                    for (j = 2; j <=num / 2; j++)
                    {
                        result = i % j;
                        if (result!=0)
                            Console.WriteLine(i);

                     }



                    



                }
                Console.ReadLine();

            }
        }
    }
}

If I put 5 , it is still ok.( output shows 235)
but If I put 7 or 9 or larger number then the outputs are not correct .(out put shows 23455777)

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

A prime number is ...
any natural number greater than 1 that has the two divisors 1 and itself
(defined in: http://en.wikipedia.org/wiki/Prime_number)

Your algorithm is pretty bad, take a look at this C# code snippet at DaniWeb to help you out:
http://www.daniweb.com/code/snippet676.html

Member Avatar
FoX_
Junior Poster in Training
53 posts since Mar 2007
Reputation Points: 0 [?]
Q&As Helped to Solve: 7 [?]
Skill Endorsements: 0 [?]
 
0
 
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            bool current = false;
            int j;

            Console.WriteLine("Enter any integer");
            int num = Int32.Parse(Console.ReadLine());

            for (int i = 2; i <= num; i++)//2 is the first prime number.
                                          //I set i to 2 beacuse it has to print 2 firstly...  
            {
                for (j = 2; j < i; j++)
                {
                    if (i % j == 0)//Controls i is prime number or not...
                    {
                        current = true;
                        break;//breaks for not controlling anymore...
                    }
                }
                if (current == false)
                    Console.Write("{0} ", j);//if i is prime number, print it...
                else
                   current = false;   
            }

            Console.ReadLine();



        }
    }
}
Member Avatar
puneetkay
Junior Poster
122 posts since Nov 2007
Reputation Points: 40 [?]
Q&As Helped to Solve: 23 [?]
Skill Endorsements: 0 [?]
 
0
 

Hie guys!

Heres something i have created to display all the prime numbers from zero up to the number entered by user.

using System;
class pnumber
{
public static void Main()
{
int value; // Value Enter By User!
int count,count2; // For inner & outer loop
int prime; // used to check prime number

Console.WriteLine("Welcome To My Program\nPlease enter a number to check whether its a prime number or not!");
value=Convert.ToInt32(Console.ReadLine());
for(count=2;count<value;count++) // Outer loop
{
prime = 1; // to set prime value to 1 every time outer loop works
for(count2=2;count2<count;count2++) // Inner loop
{
if(count%count2 == 0) // If Value is divisible..
{
prime = 0; // Set prime to 0
}
}
if(prime==1) // If prime value is 1 then...
Console.WriteLine("{0} Is Prime Number",count); // display count variable
}
}
}

This code works fine for me!

Member Avatar
rhoit
Junior Poster in Training
85 posts since Dec 2007
Reputation Points: 0 [?]
Q&As Helped to Solve: 5 [?]
Skill Endorsements: 0 [?]
 
0
 

Some how the program is correct but the algorithm is not efficient of the large no.

see this link
http://www.daniweb.com/code/snippet809.html

Member Avatar
puneetkay
Junior Poster
122 posts since Nov 2007
Reputation Points: 40 [?]
Q&As Helped to Solve: 23 [?]
Skill Endorsements: 0 [?]
 
0
 

Some how the program is correct but the algorithm is not efficient of the large no.

see this link
http://www.daniweb.com/code/snippet809.html

Hie Rhohitman,

Thanks buddy for snippet link but you are on C# section & thats a C++ snippet. :D

Member Avatar
slogfilet
Newbie Poster
1 post since May 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Some how the program is correct but the algorithm is not efficient of the large no.

see this link
http://www.daniweb.com/code/snippet809.html

I wrote something similar in C++, but the concept is the same... instead of using modulus with every ineger less than num, try this:

for (int i = 2; i <= sqrt(num); i++)


once i becomes larger than the square root of num, you're doing the same work over again!

you can also restrict it to only divide by ODD numbers, which theoretically cuts your processing time in half.

i ended up playing with an array, adding each new prime number to the array, adn only testing num against those values. worked pretty well, if i recall

Member Avatar
gauravm2k7
Newbie Poster
1 post since Nov 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-2
 
using System;
class g9{
	public static void Main(){
			int num;
			Console.Write("Enter the number till you want Prime Number : ");
			num=Convert.ToInt32(Console.ReadLine());	
			for(int i=2;i<=num;i++){
				if(i<=5 && i!=4){
					Console.Write(i+" ");
				}
					if(i%2!=0 && i%3!=0 && i%5!=0)
					Console.Write(i+" ");
				
			}
		}
}
Member Avatar
Ryshad
Nearly a Posting Virtuoso
1,263 posts since Aug 2009
Reputation Points: 480 [?]
Q&As Helped to Solve: 247 [?]
Skill Endorsements: 14 [?]
 
1
 

Any time you are having troubles with iterations like this (especially nested) your first step should be to run through it step by step and track each variable at each stage:

num = 9:

i	j	i%j	output
3	2	1	3
3	3	0	
3	4	3	3
4	2	0	
4	3	1	4
4	4	0	
5	2	1	5
5	3	2	5
5	4	1	5
6	2	0	
6	3	0	
6	4	2	6

This allows you to see exactly whats going on and why the results arent what you expect. I wont tell you how to rewrite your algorythm as there are plenty of examples already here, just thought i'd chip in with some advice on solving similar issues in the future.

Give a man a solution, and his problem is solved for today; give him the tools to trouble shoot his work, and his problems are solved for a lifetime ;)

Member Avatar
ddanbe
Posting Expert
5,354 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

@Ryshad
Yes, I do this also when confronted wih this kind of "problems".
Although these days I prefer the wonderfull debugger that comes with VS!

Member Avatar
apegram
LINQ!
550 posts since Jan 2010
Reputation Points: 302 [?]
Q&As Helped to Solve: 137 [?]
Skill Endorsements: 10 [?]
Team Colleague
 
0
 

My algorithm below is similar to what slogfilet suggested: I consider using anything beyond the square root of the integer candidate to be redundant and a waste of time to use as a test divisor.

I'm not accepting user input, nor am I writing the prime numbers to the screen, but it's easy enough to add that in (actually, the writing to the screen is simply commented out). I was more interested in seeing how fast I could get the program to run, hence the use of the stopwatch. It's under 300 milliseconds to get all primes up to 1,000,000 on my machine, just about 5 seconds to go up to 10,000,000, and of course will increase significantly from there. That's the price of using nested loops on growing lists. But I'm not done working on it, and I'm not going to assume I know enough about C# to say that I've thought of the best looping structure.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        List<int> primes = new List<int>();
        primes.Add(2);

        for (int i = 3; i < 1000000; i += 2)
        {
            bool isPrime = true;
            int stoppingPoint = (int)Math.Pow(i, 0.5) + 1;
            foreach (int p in primes)
            {
                if (i % p == 0)
                {
                    isPrime = false;
                    break;
                }

                if (p > stoppingPoint)
                    break;
            }

            if (isPrime)
            {
                primes.Add(i);
                //Console.WriteLine(i);
            }
        }

        stopwatch.Stop();
        Console.WriteLine("-- {0}", primes.Count);
        Console.WriteLine(stopwatch.ElapsedMilliseconds);
        Console.Read();
    }
}
Member Avatar
iajm
Newbie Poster
1 post since Mar 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-1
 

Thank you for going over this step by step. I am a self taught new programmer and this has helped me.

Member Avatar
__avd
Posting Genius (adatapost)
6,703 posts since Oct 2008
Reputation Points: 1,811 [?]
Q&As Helped to Solve: 1,272 [?]
Skill Endorsements: 61 [?]
Moderator
 
0
 

Welcome iajm,

I'm glad you found it useful. Have you noticed that the current thread is two years old? Please do not resurrect old/solved threads. If you want to ask question, start your own thread.

Read before posting- http://www.daniweb.com/forums/thread78223.html

Member Avatar
AnandPathak
Newbie Poster
1 post since Mar 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-1
 
private string  isPrime(string text)
        {
            int num = Convert.ToInt32(text);
            int ctr = 2;
            while (ctr <= num)
            {
                if (num % ctr == 0)
                    break;
                ctr++;
            }
            if(ctr==num)
                return "prime number"; return "not a prime number";

        }
Member Avatar
peace03951a0544
Newbie Poster
1 post since Jun 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi friends

Here i am using simple logic to get prime numbers from 1 to N numbers.

using System;
using System.Collections.Generic;
using System.Text;
namespace prime
{
class Program
{
static void Main(string[] args)
{
int a,n,i;
Console.Writeline("Enter ur number");
n=Convert.ToInt32(Console.Readline());
for(i=0;i<=n;i++)
{
if((i%2==0)&&(i%i==0))
{
a=i;
Console.Writeline("The prime numbers are",a);
}
}
Console.Readkey();
}
}
}

Output:
Enter number:9
The prime numbers are :2 3 5 7 9

Explanation:

modulus will take reminder as output as all we know.

If we write only i%2==0 it won't print 2 as a prime number.
so, i wrote i%i==0 here.
Output will come if and only if both conditions are true

Member Avatar
mdaz
Newbie Poster
1 post since Jun 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Can you please explain it in a simple way.

Member Avatar
Momerath
Senior Poster
3,830 posts since Aug 2010
Reputation Points: 1,327 [?]
Q&As Helped to Solve: 664 [?]
Skill Endorsements: 19 [?]
Featured
 
0
 

Could you not reply to threads that are over a year old? If this doesn't help you, start a new thread.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: