Question

Prime numbers C++ program. Please help.

Asked by: zainab_alkhamis

Write a program that finds and prints all of the prime numbers between 3 and 100.  A prime number is a number such that one and itself are the only numbers that evenly divide it ( e.g., 3, 5, 7, 11, 13, 17 ... ).
One way to solve this problemis to use a doubly nested loop.  The outer loop can iterate from 3 to 100 while the inner loop checks to see if the counter value for the outer loop is prime. One way to see if number n is prime is to loop from 2 to n-1 and if any of these numbers evenly divides n, then n cannot be prime. If none of the values from 2 to n-1 evenly divide n, then n must be prime. ( Note that there are several easy ways to make this algorithm more efficient.)

Please someone help me, it's a take-home test project, and I am totally sleepy, I tried many ways to solve it but it didn't work.  Anyone? Please? I need the whole project, because I have another one about liters and gallons but I'll try to do it my own.  I'm so stuck. =[

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-01-13 at 10:09:09ID23079279
Topics

Windows 95 - 98 Networking

,

Miscellaneous Programming

,

C++ Programming Language

Participating Experts
4
Points
504
Comments
31

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

    Free Tech Articles

    1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
      It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
    2. SCCM OSD Basic troubleshooting
      SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
    3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
      This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
    4. Create a Win7 Gadget
      This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
    5. Outlook continually prompting for username and password
      There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
    6. Backup Exchange 2010 Information Store using Windows Backup
      There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

    Cloud Class Webinars

    1. Avoiding Bugs in Microsoft Access
      Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
    2. Top 10 Best New Features in Visio 2010
      Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
    3. IT Consultant Business Secrets Revealed
      Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
    4. Disaster Recovery and Business Continuity
      Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
    5. Organize Your Visio Diagrams with Containers and Lists
      Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
    6. How to Us Objects, Properties, Events and Methods in Microsoft Access
      Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

    Join the Community

    Give a Little. Get a Lot.

    Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

    Join the Community

    Answers

     

    by: Infinity08Posted on 2008-01-13 at 10:11:53ID: 20648491

    >> I tried many ways to solve it but it didn't work.

    Can you show what you tried, and tell where exactly you are stuck ?


    Since this is an assignment, we can't solve it for you, but we will help you solve it yourself ...

     

    by: zainab_alkhamisPosted on 2008-01-13 at 10:24:44ID: 20648529

    Geee, I swear to God I had to just remove all the info, because it simply gave me tons of errors, it just doesn't work ... I'm helpless.

     

    by: Infinity08Posted on 2008-01-13 at 10:29:38ID: 20648545

    >> it just doesn't work ... I'm helpless.

    Can you still post what you have ? You must have gotten somewhere at least, especially since the assignment is very specific about what you have to do :

            "The outer loop can iterate from 3 to 100 while the inner loop checks to see if the counter value for the
              outer loop is prime. One way to see if number n is prime is to loop from 2 to n-1 and if any of these numbers
              evenly divides n, then n cannot be prime. If none of the values from 2 to n-1 evenly divide n, then n must be
              prime."

    Which part of this gives you trouble ?

    Have you written programs in C++ before ?

     

    by: zainab_alkhamisPosted on 2008-01-13 at 11:10:03ID: 20648694

    I've only done a simple one and all of a sudden she gave us something that she didn't even bother to explain and just wants us to figure it out ourselves. =S
    I'm not a genius or can predict things or have some super powers.  That's why I need help, gosh. =[
    I couldn't work it out at all.  I dunno even know what is a nested loop ... gee.  I'm not joking when I said I'm helpless.

     

    by: Infinity08Posted on 2008-01-13 at 11:23:44ID: 20648751

    Ok, in that case, I would start out by reading up on C++. Here are a few tutorials to get you up-to-date :

            http://www.cplusplus.com/doc/tutorial/

    It's a recommended read !


    Regarding your specific question :

    >> I dunno even know what is a nested loop

    A nested loop is one loop inside the body of another. For example two nested for loops :

            for (int i = 0; i < 10; ++i) {
                for (int j = 0; j < 20; ++j) {
                    // some code
                }
            }

    So, the inner for loop (the one with j as index) will be executed 10 times. The total amount of times that "some code" will be executed is thus 10 * 20 = 200 times.

    Does that make sense ?

     

    by: zainab_alkhamisPosted on 2008-01-13 at 11:29:19ID: 20648775

    Yeah, it does.  But I kind of don't know a lot about that.
    Thanks for the help really, though I don't think I'll be able to actually do my assignment, because it needs practice, and it's already night and oh well.  It's not my fault that I do not understand, it's just she gives us things that she didn't even bother to explain ....

    Thanks a lot anyway ...

     

    by: Infinity08Posted on 2008-01-13 at 11:30:58ID: 20648782

    >> But I kind of don't know a lot about that.

    That's why I posted the basic C++ tutorials ... Did you read them ?

     

    by: zainab_alkhamisPosted on 2008-01-13 at 11:32:58ID: 20648792

    I am working on it.  I'll try my best.

    However, it would be a really great favor if you know how to do it.  You won't lose anything, and I don't really rely on others when I want to do my homeworks and stuff, that's not me, but this was urgent so I thought of asking.  But still thanks if you don't want to do it, I don't blame you. =]

     

    by: Infinity08Posted on 2008-01-13 at 11:35:14ID: 20648803

    I'm sure you understand, but if I give you the solution, then I've deprived you of a good learning experience, and I don't want to do that.

    If you want to give it a try (don't give up ;) ), however, I will be here to help you with any problems/questions you might have. What do you think ?

     

    by: Infinity08Posted on 2008-01-13 at 11:36:34ID: 20648807

    Just take it one step at a time : start with the basic skeleton of a C++ application, and then add code to it, one bit at a time, until all requirements are met.

    But first make sure that you understand the assignment. I assume you know what prime numbers are ?

     

    by: zainab_alkhamisPosted on 2008-01-13 at 11:37:26ID: 20648811

    Alright, I'll work on it with you then, and we'll see. =]
    Don't you have msn messenger, it would be even easier?

     

    by: Infinity08Posted on 2008-01-13 at 11:38:09ID: 20648815

    I'm monitoring this thread, and I'm able to respond very fast ;)

     

    by: zainab_alkhamisPosted on 2008-01-13 at 11:39:29ID: 20648819

    Hehe, okay, I'll start now, and I'll see what I need.

     

    by: zainab_alkhamisPosted on 2008-01-13 at 11:41:26ID: 20648831

    I know that I should use a for loop because there is calculating, I hope I'm right.  But I dunno what to include in that for loop.

     

    by: Infinity08Posted on 2008-01-13 at 11:44:08ID: 20648841

    Take it one step at a time ... Do you know what prime numbers are ? If not, they're numbers that are divisible only by themselves and by 1.

    If you're wondering about what should be in the for loops, read the assignment : it's very specific about that. Just give it a go, and write some code (one step at a time as I said earlier), and post it here ... that's the easiest way :)

     

    by: zainab_alkhamisPosted on 2008-01-13 at 11:48:06ID: 20648866

    for ( int n = 3, n >= 100, n++)

    I feel stupid ... =S

     

    by: Infinity08Posted on 2008-01-13 at 11:52:49ID: 20648883

    Start with the skeleton of a C++ program. Check this tutorial for that :

            http://www.cplusplus.com/doc/tutorial/program_structure.html

    I assume you have a compiler ready, and know how to use it ?


    >> for ( int n = 3, n >= 100, n++)

    A for loop consists of 3 parts :

            1) the initialization : this is set at the beginning of the loop
            2) the loop condition : as long as this is true, the loop will continue
            3) the increment : this is done at the end of each iteration

    and is structured like this :

            for (<initialization>; <loop condition>; increment) {
                // loop body
            }

    Note that a ; is used to separate the 3 parts (that's your first problem). Also note that the loop condition, is the condition that needs to be fulfilled as long as the loop runs. As soon as this condition becomes false, the loop ends. So it needs to be :

            for ( int n = 3; n <= 100; n++)

     

    by: zainab_alkhamisPosted on 2008-01-13 at 11:56:14ID: 20648889

    #include <iostream>
    using namespace std;
    int main()
    {
    for (int n = 3; n <= 100; n++)

    I can do this so far .. =S

     

    by: Infinity08Posted on 2008-01-13 at 11:58:14ID: 20648900

    >> I can do this so far .. =S

    You forgot the last part ;)

    You still haven't answered my question : do you know what prime numbers are ? Do you understand the assignment - what you're supposed to do ?


    #include <iostream>
    using namespace std;
     
    int main() {
     
        for (int n = 3; n <= 100; n++) {
            // TO DO
        }
     
        return 0;
    }
    
                                                  
    1:
    2:
    3:
    4:
    5:
    6:
    7:
    8:
    9:
    10:
    11:
    

    Select allOpen in new window

     

    by: zainab_alkhamisPosted on 2008-01-13 at 12:01:25ID: 20648907

    I know what prime numbers are of course, but I can't do them in C++ programming, only math, lol.

    Aaaah, okay, I know that I should print all the prime numbers from 3 to 100 in the first loop.  But I just don't know how.  I feel like crying.  Pfft.

    Oh and by the way, I know that I was supposed to put return 0; but I didn't because the program isn't over yet hehe.  It's like I didn't even start.

     

    by: Infinity08Posted on 2008-01-13 at 12:05:06ID: 20648919

    >> Aaaah, okay, I know that I should print all the prime numbers from 3 to 100 in the first loop.

    Indeed. Now, the loop goes from 3 to 100. If you put :

            cout << n << " ";

    inside the loop, the code will print out all numbers from 3 to 100 (try it to see what I mean).

    We don't want to print all numbers - we want to print ONLY the prime numbers. So, for each number, we'll have to find out whether it's a prime or not. If it's a prime, we print it, if it's not, we don't print it.

    How can we know whether a number is a prime ? That's nicely explained in the assignment. Take a look at it, and try to add the code for that.

     

    by: zainab_alkhamisPosted on 2008-01-13 at 12:09:48ID: 20648934

    We divide by 2 to see if it's prime or not?
    Umm the cout << n << " "; thing .. what do I put between "  " .. do Ihave to list the whole numbers for 3 to 100? =O
    I don't get it yet ..

     

    by: Infinity08Posted on 2008-01-13 at 12:14:47ID: 20648954

    >> We divide by 2 to see if it's prime or not?

    A prime is a number that is divisible only by itself and by 1. If it's divisible by any other value, then it's not a prime. You need to check whether the number n is divisible by any value between 2 and n-1. As it says in the assignment :

            "One way to see if number n is prime is to loop from 2 to n-1 and if any of these numbers evenly divides n,
              then n cannot be prime."


    >> Umm the cout << n << " "; thing .. what do I put between "  "

    Nothing. " " is just a space. Try putting it inside the for loop we had earlier, and compile it. Then run it, and see what happens. Writing a program is constantly adding code, then running it to see whether the added code does what it's supposed to do.


    >> do Ihave to list the whole numbers for 3 to 100?

    Not for the assignment no. For the assignment, you only need to list the prime numbers between 3 and 100.

     

    by: zainab_alkhamisPosted on 2008-01-13 at 12:17:01ID: 20648963


    #include<iostream>
    using namespace std;
    int main()
    {
          int n, prime;
          
          for(int n = 3; n <=100 ; n++)
          {
                prime = 2;

     

    by: Infinity08Posted on 2008-01-13 at 12:18:46ID: 20648971

    You forgot the last part again ... When writing programs, it's best to be very strict. Otherwise, you'll make errors.


    Can you tell me what you were trying to do in that code ?

    Did you understand my last post ?

    Do you understand the assignment ?

     

    by: evilrixPosted on 2008-01-13 at 12:19:51ID: 20648976

    Regarding your problem with prime numbers, it's a typical homework problem and as such there are any number of tutorials and examples on the web! Try Googl'ing for "C++ Prime Numbers" and checking out a few of the links. At EE the experts cannot and will not provide you with full code solutions; however, Infinity08 is very good at maths related problems and is especially patient -- you are in good hands :)

    >> I know that I was supposed to put return 0;

    Actually, that's not strictly true, since (according to the standard) main() in C++ doesn't actually have to return anything (it just has to be defined to have a return type of int). It is; however, it is good practice to get into the habit of always returning a value form main. Usually, 0 is used to indicate success any other value conventionally means an error has ocurred.

    "A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;"


     

    by: Infinity08Posted on 2008-01-13 at 13:03:52ID: 20649140

    zainab_alkhamis, I haven't heard from you in a while now ... Are you still there ?

     

    by: itsmeandnobodyelsePosted on 2008-01-14 at 04:47:22ID: 20652512

    >>>>      for(int n = 3; n <=100 ; n++)
    >>>>      {

    ok. that for loop repeats 98 times iterating n from 3 to 100 (both edges including).

    To print the primes only you simply have to find out whether a 'n'  divides by numbers lower than 'n'. Without optimizations that simply can be done by adding a nested loop (Infinity already explained what that is) which tries:

              for (int i = 2; i < n; ++i)
              {

    That inner loop would run from 2 to n-1 where 'n' is the 'n' of the outer loop.

    to test for prime you now have check whether 'n' can be divided by 'i' without rest. For that the modulo operator % is useful which computes the rest of an division, i. e.   the term 'n % i' is the rest of 'n / i' and must not be 0 if n is a prime.  Otherway round, in case 'n%i' is 0 you could break the inner loop with a 'non-prime'  result, as the test has proven n isn't a prime.

                   if (/* put here the modulo term */  ...  == 0)
                   {
                          isprime = false;
                          break;
                   }

    The 'isprime' is a bool helper which must be set to true above the inner loop:

          bool isprime = true;
          for (int i = 2; i < n; ++i)
          {
                  ....

    After the inner loop you have to decide whether to print 'n' as a prime or not. Fortunately, you only need to test on the 'isprime' already filled correctly.

          if (isprime)  // means the inner loop didn't find a reason to break
                cout << /* output a statement that n is prime */  .... << endl;

    If the program works, you should optimize it:

    1. Run the outer loop with a step of 2 as no prime can be a multiple of 2.

          for (.....; n += 2)

    2. Run the inner loop starting with 3  (as the even n already were filtered)

    Make a step of 2 as well cause n is an odd number and no odd number can be dividided without rest by an even number.

    3. Make the upper boundary of the inner loop the sqare root of n.

    Any integer i greater than the square root cannot be a divisor of n.

    Regards, Alex

     

    by: AlexNekPosted on 2008-01-15 at 16:16:29ID: 20668180

    First, try to find primes manually for a small range.
    Second, try to describe your algorithm.
    Third, write your program with pseudo code.
    Fourth, convert pseudo code to programming language.

    Some tips for you:
    First suggestion - all numbers from our "small" range could be prime. Remove all numbers that definitively not prime from this range. /Numbers that divided by 2, at least/
    You can try to divide all items from resulting sequence by the start items /3,5,.../ if you can divide any item then remove it from sequence. If any numbers couldn't be divided by any previous then you are found all primes.
    Optimization tip: It is no sense to check if 21 can be divided by 11 /21/2 = 10.5, 11>10.5/

    20120131-EE-VQP-002

    3 Ways to Join

    30-Day Free Trial

    The Experts

    98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

    He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

    The Experts

    97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

    The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

    Testimonials

    "...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

    Testimonials

    "I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

    Testimonials

    "WOW! You guys have great, active, and knowledgeable people on here." moore50

    Business Clients

    Business Clients

    In the Press

    "If you’ve got a question... Experts Exchange can supply an answer.”

    In the Press

    "...an invaluable aid for both IT professionals and those who require tech support."

    In the Press

    "where IT professionals provide quick answers on just about any topic"

    Business Account Plans

    Loading Advertisement...