C Algorithm to Show n is a Prime Number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dinesh Kumar bca
    New Member
    • Aug 2008
    • 1

    C Algorithm to Show n is a Prime Number

    Hai...I am a very basic student for C...So many apologies for asking this basic question. My question is, How to write algorithm for the program to given n number is prime number? Please help.......
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Have you tried Google on this?

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      As you know a prime number is one which can only be divided by 1 or itself.
      So (ignoring these two) if the number can be divided by 2,3,5,7,9...... ...etc it is not prime. If not it is prime. I think that is the algorithm for determining whether a number is prime or not. Could you write some code to reflect this algorithm?
      e.g.
      Code:
       if(n%2==0)cout<<"n is not prime"<<endl;

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by whodgson
        Code:
         if(n%2==0)cout<<"n is not prime"<<endl;
        Nitpick: what about n == 2?

        kind regards,

        Jos

        Comment

        • whodgson
          Contributor
          • Jan 2007
          • 542

          #5
          Yep, as everyone knows 2 is the only even prime

          Comment

          • mstab
            New Member
            • Aug 2008
            • 1

            #6
            a basic solution is as follows,

            this in not optimised, ie very inefficient, can be improved considerably
            an lends itself to a recursive solution.

            Code removed per posting guidelines

            Comment

            • newb16
              Contributor
              • Jul 2008
              • 687

              #7
              You do not need dividers greater thatn sqrt(n) to check.
              let alone that this loop will execute only once for odd N. ( 0==ret )

              Comment

              Working...