Please point out the logic errors in this simple program

Jun 2, 2013 at 9:21pm
There are logic errors in the program. Mainly in the for loop. Please point them out. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  #include <iostream>
#include <cmath>

#define PROMPT "Please enter a whole number:"
#define NOT_PRIME "The number is not a prime number./n"
#define PRIME "The number is a prime number./n"
#define DONE 0          /* ends successful program */
#define FIRST_FACTOR 3  /* initial value in for loop */

using std::cout;
using std::cin;

int main(){
    
    int i;       /* loop counter */
    int number; /* number provided by user */
    
    cout << PROMPT;  /* promt user */
    cin >> number;  /* wait for user input */
    
    /* Prime numbers are defined as any number
     * greater than one that is only divisible
     * by one and itself. Dividing the number
     * by two shortens the time it takes to
     * complete. */
    
    for(i = FIRST_FACTOR; i < number/2; ++i)
        if( number/i == 0 ){    /* if divisible */
            cout << NOT_PRIME << number; /* not prime */
            return DONE;        /* exit program */
        }
    
    /* if number is not divisible by anything
     * than it must be prime */
    cout << PRIME << number;
    return 0;     /* exit program */
}
Jun 2, 2013 at 9:34pm
The logic errors, right off the bat, would be dividing by every single number- including numbers that aren't prime in the first place. Two, there's no need to define DONE to be 0- hell, 0 is shorter than DONE, so that's pointless. Actually, all of those defines are pointless. Three, you can declare the loop counter in the loop itself to keep it local to the loop. Four, you can input negative numbers, since it does not check for those (it will just say the number is prime). Five, dividing the number by two initially is foolish because the number is an integer, thus allowing, say, 2 to be read as prime. Six, you are using the wrong division method- you want modulus, not standard division. And seven, you include cmath without using anything specifically from cmath.
Last edited on Jun 2, 2013 at 9:35pm
Jun 2, 2013 at 9:42pm
@Ispil
I think this is a homework assignment the poster wants us to finish for him/her.
Considering Jinganinja1's past threads, I don't hold much optimism that this isn't true.
Jun 2, 2013 at 9:46pm
Well, they'll fail their tests at the end of the year, then. Not my problem, really.
Jun 2, 2013 at 9:54pm
You also want to use % to see if it has a remainder. Instead of /. So do your code as
if (number%i==0)

Also a prime number is a natural number meaning numbers that aren't negative. Besides the part that it can only be divided by 1 and itself :P
Last edited on Jun 2, 2013 at 9:58pm
Topic archived. No new replies allowed.