Like Tree9Likes

Prime number question code

This is a discussion on Prime number question code within the C++ Programming forums, part of the General Programming Boards category; Alright, from an article I tried to find the prime number and from my research I found a solution (which ...

  1. #1
    Registered User
    Join Date
    Oct 2013
    Location
    Hellas
    Posts
    70

    Prime number question code

    Alright, from an article I tried to find the prime number and from my research I found a solution (which is not mine) and I need help on underestanding it.
    Here is the code:
    Code:
    #include<iostream>
    using namespace std;
    int main()
    {
    int num;
    cout<< "Enter a number ";
    cin >> num;
    int i=2; //why I set i to 2?
    while(i<=num-1) //why I must num-1???
    {
    if(num%i==0)
    {
    cout << "\n" << num << " is not a prime number.";
    break; //breaks from where to where?
    }
    i++; //why the heck again I must add to i+1?
    }
    if(i==num)
    cout << "\n" << num << " is a prime number.";
    return 0;
    }
    I have tried reading tutorials but it's of no use.. Can someone explain it to me?

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    2,767
    Look up the definition of prime numbers; 1 is defined to NOT be prime.
    A number is always the product of itself times 1.

    Edit: http://www.cprogramming.com/tutorial/c/lesson3.html

    If the value in the loop test "i<=num-1" does not change you will normally have an endless loop that is why the i++ is in the code.

    Tim S.
    Last edited by stahta01; 10-11-2013 at 11:43 AM.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the Universe is winning." Rick Cook

  3. #3
    Registered User
    Join Date
    Oct 2013
    Location
    Hellas
    Posts
    70
    I did not get a thing.... Neither you explained about break bro.. I already said that I have read the tutorial, so if you may like I would like an answer of "Why I set it to 2"? = Because.....
    "Break; breaks from where to where" = breaks from this to there

    I think that those kind of answers (direct ones) would have been simple and very underestandable. Sorry if I seem to be a little aggresive, I didn't mean to.. It just gets on my nerves when I have spent a day on sth, try to ask for help and the help redirects me to what I have read BUT did not underestand for any reason...

  4. #4
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,761
    You set i to 2 because your search must start at 2 by the definition of prime numbers: a prime number is an integer greater than 1 which has no divisors other than itself and 1.

    I'd give you an answer about break; in the form of ""Break; breaks from where to where" = breaks from this to there" but I can't. Exactly what happens with break depends on the context. I'm not sure if my answer will be helpful since you have reading comprehension problems, but here it goes:

    break's purpose is to force execution to leave the surrounding block. You should be familiar with code executing in top down manner, starting in main(); well, break changes the flow of execution. Used in a loop, execution will immediately leave the nearest loop and would pick up after, say, a closing brace. Nearest loop is to say that a break in a nested loop would not stop the outer loop. Used in a switch case, break will prevent execution down to the next case, and execution would pick up after the switch's closing brace.

    Continue is different. Continue forces a loop's condition to be evaluated immediately, therefore starting a new iteration, no matter what is written below continue.

  5. #5
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,761
    And as for the other questions, do you have any idea what the loop is actually doing? I'd like to hear your thoughts on how this works, rather than just your questions.

  6. #6
    Registered User
    Join Date
    Oct 2013
    Location
    Hellas
    Posts
    70
    First of all I never had reading comprehension problems and never will I get... I don't have a teacher to fully underestand C++ and unlike (probably) any of you here I start from scratch using tutorials from the internet which is extremely difficult... Any way, I don't expect you to underestand.. By saying "I did not get a thing" to stahta01 I didn't mean that I didn't underestand english, I meant that he should be more detailed on his answer because he deals with a beginner and he is laconic..

    Let's take this:
    Code:
    while(i<=num-1) //why I must num-1??? { if(num%i==0) { cout << "\n" << num << " is not a prime number."; break; //breaks from where to where? } i++;
    I have read about break; and it's use on a program but I cannot underestand why I must put brake; on the upper code since the program will either way 'break' on itself from this statement on the closing brace
    Closing, we have i+1 (i++) , why i must be incremented ???
    Last edited by Innos; 10-11-2013 at 04:47 PM.

  7. #7
    Registered User
    Join Date
    Oct 2013
    Location
    Hellas
    Posts
    70
    Quote Originally Posted by whiteflags View Post
    And as for the other questions, do you have any idea what the loop is actually doing? I'd like to hear your thoughts on how this works, rather than just your questions.
    Loop is used to repeat a block of code, meaning a block of code we mean the content which is enclosed within 2 braces
    Code:
    ({) and (})

  8. #8
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,761
    Loop is used to repeat a block of code, meaning a block of code we mean the content which is enclosed within 2 braces
    Hopefully I'll show you why this answer is short sighted in a minute.

    I have read about break; and it's use on a program but I cannot underestand why I must put brake; on the upper code since the program will either way 'break' on itself from this statement on the closing brace
    Closing, we have i+1 (i++) , why i must be incremented ???
    None of this is all that relevant to what is actually happening. Since you don't understand break, it can be frustrating to see code with it in there, but this example doesn't need to use it. It's just written that way.

    The code itself seeks to confirm if a number the user enters is prime or not. The example code used a brute force method called trial division. We will simply divide the user's number by all the integers before it, and if none divide evenly, then we have a prime. Let's pick a prime example and a composite example and see what happens.

    >> i = 2;
    >> while (i <= num - 1)
    We start searching with the variable i set to 2, because 1 is not prime (it is a unit, and therefore it divides every integer).

    Code:
    if (num % i == 0) 
    {
       cout << "\n" << num << " is not a prime number.";
       break;
    }
    The initial test. We test if a number is divisible by 2. If it is, then we can quit imediately. Let's say that num is 5, so it fails. We skip down to...

    >> i++;
    After this statement, the loop starts a new iteration.

    >> while ( i <= num - 1 )
    Well, now i is 3, and it's still less than or equal to 5 - 1.

    >> if (num % i == 0)
    Another test, and it still fails.

    >> i++;
    New iteration next!

    >> while (i <= num - 1)
    4 is less than or equal to 4, but anyway, we've come up on the final iteration. After this, we decide one way or another.

    >> if (num % i == 0)
    So is 5 divisible by 4? of course not.

    >> i++;

    >> while (i <= num - 1)
    Finally false. So we have to continue after the loop!

    >> if (i == num)
    If you've been following along, counting the number of times we incremented i, then you know that this is true. So we do the stuff underneath this if: print that it's a prime number.

    Now what if the number was composite? Lets do it again with 4,

    >> i = 2.
    >> while (i <= num - 1)
    Well 2 is less than 3.

    >> if (num % i == 0)
    4 is divisible by 2, so we have to do the stuff underneath: print that it is not a prime, and break. Break quits the loop, so we go all the way down here, which happens to be the code after the loop.

    >> if (i == num)
    And that's false...

    If you never internalized that we were looking for a prime number that is equal to the number the user entered, you wouldn't understand why we're dividing. And we're dividing because if i ever divides cleanly, then it is a divisor of num, and num is composite.

    Well, anyway, here's my suggestion. Stop wondering about particular implementations and start trying to solve problems with what you learn. Look at the code with fresh eyes and try to rewrite it without break. It can be done. The real question is, how do you write a program that confirms what number the user entered is prime? What math can you use? If you don't understand the problem, a correct program cannot be written.

    I first learned programming with the help of a book and because I wanted to do something with the code I was writing. I wanted to have a web site, and I made several bad ones. A lot of them had ........ty Javascript cursors and moving pictures and... well. I did something with what I was learning that went beyond the keywords themselves. I hope you don't mind me saying, but you need to work out why you're programming.

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,628
    Quote Originally Posted by Innos View Post
    I didn't mean that I didn't underestand english, I meant that he should be more detailed on his answer because he deals with a beginner and he is laconic..
    Being a beginner does not mean you are entitled to receive an answer in the form that suits you. It means YOU need to apply effort to interpret answers that may not be in exactly a form that is ideal for your comprehension.

    The real world does not tailor its problems for you. It certainly does not give you answers in a way that are always convenient to you. While it is possible to adapt parts of the real world to yourself, that takes hard work on your part. It is more usual that you will need to adapt yourself to the world.

    staha01 answered two of the three questions in your original post. The onus is on you to fill in any gaps in your understanding, not his.
    stahta01 likes this.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

  10. #10
    Registered User
    Join Date
    Oct 2013
    Location
    Hellas
    Posts
    70
    You're wrong. When you see someone who says "I've spent a day on this, please help", you better give him a good explanation on what he seeks, or if you wish to be laconic just don't post and add to the confusion. Being a beginner means a lot of hard work from my side and yes mate I expect an answer that suits me after 1 day of hard work. When I ask for help, I have read everything that I can find on the internet and still can't find a solution (it's simple logic for someone who asks a question, else he wouldn't ask - mind that the person who asks deals with his problem in a serious matter and DOES actually look for hints to his problem on inernet). In any way, if the one who helps doesn't really help (in any way) the one asking for help, then he didn't really help, so...

    The onus is on you to fill in any gaps in your understanding, not his.
    If you cannot help because you are bored to give an explanation (a laconic explanation is an explanation out of boredom, either you want to admit it or not), then don't post and don't add to the confusion. It's as simple as that.

    Thanks to all who answered nevertheless and thanks whiteflag for a detailed answer, I got it now.

  11. #11
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,761
    I'm glad that you liked my answer, but I am probably not going to be that helpful again. You've seen me trace code step by step, and I expect that if you are learning anything, you will be able to do that with your own code, by yourself, from now on.

    Why this response? You are an expert at lip service. How hard was your day really if you spent it all on this and you couldn't even begin to tell me anything about the program?

    In fact if I had to accuse anyone of terseness, it's you. I certainly don't appreciate that the only thing you ever have to say about your problems are "I don't understand this" or "Why do we do that?" Believe it or not, framing a discussion with what you do understand and what you have already read can spur a more interesting discussion. It also shows that you are making an effort and care about the subject. Otherwise, I don't see why it's unreasonable to assume that you have read nothing on the subject, and thus be helpful, not malicious, by linking you to such resources. We don't have a crystal ball to tell us what you've read or why you don't understand anything. If you want to ask better questions and receive better help, show your work. I'm not going to sit here and respond to every utterance of "I don't get it," because you could very easily deliberately not "get it" for eternity, and you could take the easy road in life. No human being explains his entire profession to a layperson.

    Check yourself before you wreck yourself.
    stahta01 and Sebastiani like this.

  12. #12
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by Innos View Post
    You're wrong. When you see someone who says "I've spent a day on this, please help", you better give him a good explanation on what he seeks, or if you wish to be laconic just don't post and add to the confusion. Being a beginner means a lot of hard work from my side and yes mate I expect an answer that suits me after 1 day of hard work. When I ask for help, I have read everything that I can find on the internet and still can't find a solution (it's simple logic for someone who asks a question, else he wouldn't ask - mind that the person who asks deals with his problem in a serious matter and DOES actually look for hints to his problem on inernet). In any way, if the one who helps doesn't really help (in any way) the one asking for help, then he didn't really help, so...


    If you cannot help because you are bored to give an explanation (a laconic explanation is an explanation out of boredom, either you want to admit it or not), then don't post and don't add to the confusion. It's as simple as that.

    Thanks to all who answered nevertheless and thanks whiteflag for a detailed answer, I got it now.
    Keep in mind that the advice given here, helpful or not, is 100% FREE. We're not obligated to tailor our explanations to your liking, and we fully expect YOU to do most of the footwork in perfecting your skills. If that doesn't work for you then HIRE a tutor...
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  13. #13
    Registered User
    Join Date
    Oct 2013
    Location
    Hellas
    Posts
    70
    It's not tailoring your explanations to my or any other beginner's liking, it's making an explanation that a BEGINNER can underestand, I do not oblige anyone to answer me but if you are going to, then do it in an underestandable way, not your way where it will be pointless since I will not underestand. If you ask me my name and I answer you, go see my family tree, would you like it? I am not saying that I haven't tried, I said that I tried to solve my problem. I tried and tried and tried and I saw that I cannot solve it if someone doesn't explain it to me in plain words.

    So your thinking is: I should pay you for trying to make an explanation that worths. Otherwise you give me your laconic answer where only you and other experts underestand because it's FREE?

    In any way, this has gone too far and off topic.. I just asked for a SPECIFIC help on some SPECIFIC lines. I said that I've read the tutorials, I said that I've read on the internet and cannot underestand and you keep up saying like bots go read this and go read that instead of answering directly. Do not want to answer directly? Then don't answer! Redirecting on what I have read already doesn't help (finally underestand that!). I am not stupid to post here my problem, wait for someone to see it, wait for someone to answer, then if I didn't underestand the answer, try to answer back and etc. I would have skipped all that by reading the topic that you redirect me.

    Simple, no? It's ok I am not going to continue this thread. Everyone has his own opinion.

  14. #14
    Registered User
    Join Date
    Jun 2005
    Posts
    6,628
    Quote Originally Posted by Innos View Post
    It's not tailoring your explanations to my or any other beginner's liking, it's making an explanation that a BEGINNER can underestand,
    Read that (part of) your post again. You have contradicted yourself.

    You have SPECIFIC requirements on what YOU can understand. You are expecting that we meet them. In other words, you expect us to tailor the explanation for YOU.

    If you want that sort of tailoring, YOU have to earn it.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

  15. #15
    Registered User
    Join Date
    Oct 2013
    Location
    Hellas
    Posts
    70
    I have not contradicted myself, you just didn't get the meaning of those 2 phrases mate..

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 05-27-2010, 01:57 PM
  2. largest number prime number that can be produced...
    By ElemenT.usha in forum C Programming
    Replies: 8
    Last Post: 02-17-2008, 01:44 AM
  3. Replies: 15
    Last Post: 11-25-2007, 03:47 PM
  4. prime number program code
    By jd7joe in forum C++ Programming
    Replies: 1
    Last Post: 11-17-2005, 10:14 AM
  5. Replies: 3
    Last Post: 03-29-2005, 04:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21