Struggling with C++ programming assignment

Hello everyone,

I've just started a degree in Info Security and Networking and one of the fundamental courses I have to take is a Programming course on C++. Right now I am doing the second assignment for this and am struggling with the second part of it.

Basically, the task is to create a program that determines whether a number is a prime number or not and then loop it so that the user inputs whether they want to enter another number or not. Right now my program is reading certain numbers such as 12, 60 wrong incorrectly by telling me that they are prime numbers when they aren't and doing the opposite with numbers such as 2.

I feel I should add that my tutor seems to be one of these guys with a really high I.Q but not much emotional intelligence and his attitude seems to be that he's not going to help me because I should already know all of this.

I'm not asking for anyone here to give me the exact answer necessarily but if someone could give me an inkling of where the problem lies so I could fix it then I'd be really, really grateful.

Thanks in advance,
William

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
38
39
40
41
42
#include <iostream>
#include <conio.h>
using namespace std;

 int main()
 {
  int input;
  int count = 2;

 char again = 'y';
 while (again == 'y') {


  cout << "Check if a number is prime \n";
  cout << "Enter a number: ";
  cin >> input;

	while (true)
				{
	if (input%count != 0)
	{
	 cout << " is not a prime number";
	 count++;
	 break;
	}
		else
	        {
		 cout << " is a prime number";
		 count++;
		 break;
		 }
				}
		cout << " do you want to do it again ? y/n ";
		cin >> again;
		cout << endl;
					 }

	   if (again = 'n')


	getch();
	return 0;
Last edited on
Hi,

Stonelands wrote:
if someone could give me an inkling of where the problem lies so I could fix it then I'd be really, really grateful

from line 20 to 28, you are checking for prime numbers... can you tell what exactly is your logic of checking prime numbers?

Last edited on
I don't think your loop is working the way you think.

I would suggest a for loop, and increase count until you reach the sqrt.

Your pretty close.
if x%y == 0 then y divided into x evenly. your if statement says if x%y isn't zero, its not prime, ... but that means it did NOT divide evenly. Also the while true loops until break is hit, but break is only hit if its possibly prime (incorrect first if statement) or always happens in the else.

lets play computer for a sec... put in 10.
is 10 % 2 even? Yes, so we do the else, increment 2 to 3. cout its a prime number. exit the loop.

or put in 7.
7 is not divisible by 2, so it says it is not prime, and exits the loop.

the simple brute force algorithm to find a prime is to divide it by everything from 2 to the square root of the number and if it divides evenly, its not prime. There are far better algorithms (this one would take a lifetime for a large value) but it works for small stuff.


Last edited on
Hi,

My logic is that if input % by count (with count=2) are not equal to 0 then it should have given the user the correct answer but with certain numbers like 60 it is giving me the opposite answer to what it should be, i.e telling me it's a prime number when it's not. Sorry if I'm not very good at explaining my thought process here but this has flustered me quite a bit.

Thanks for you help,
closed account (48T7M4Gy)
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
38
39
40
41
42
43
#include <iostream>

using namespace std;

int main()
{
    int input;
    int count = 2;
    
    bool is_prime = true;
    
    char again = 'y';
    
    while (again == 'y')
    {
        cout << "Check if a number is prime \n";
        cout << "Enter a number: ";
        cin >> input;
        
        is_prime = true; // <-- assume always true
        
        count = 2;
        while (count < input)
        {
            if (input % count == 0)
            {
                is_prime = false; // <-- only change if false
            }
            count++;
        }
        
        cout << input << " is";
        
        if(is_prime == false)
            cout << " not";
        
        cout << " prime\n";
        
        cout << " do you want to do it again ? y/n ";
        cin >> again;
    }
    return 0;
}
that is what I was trying to tell you. the logic is 1) backwards and 2) totally incorrect anyway.

all you need for brute force is:

bool isprime = true;
for(i = 2; i <= sqrt(num) && isprime; i++)
{
isprime = num%i;
}
if(isprime)
cout << "its prime"
etc....

which sets isprime to false (zero is false in C/C++) if it divided evenly. Math tells us that you can't have an integer factor bigger than the square root of the number without having encountered its buddy before that. For example, 10 .. 2 and 5, 5 is > sqrt 10 but its buddy, 2, isnt, and can't be. If both pairs were bigger than the square root, they would multiply to a number bigger than num. It isnt necessary to have the boolean and to abstract the print statement from the loop, but it demonstrates keeping the work apart from the output, which is IMHO better style and practice.


Last edited on
By definition, a prime number is any positive integer that is greater than 1 and has only two factors (1 and it self)

One way of knowing if a number is prime is by dividing the number with all numbers from 2 upto the square root of the number. If the number divides any number from 2 to sqrt(number), then it is not prime (as pointed by jonnin)

Put into code, it means something like this

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
38
39
40
#include <iostream>
#include <cmath>	// sqrt
using namespace std;

bool isPrime(int num);

int main()
{
	char again = 'Y';

	while (again == 'Y')
	{
		int num{ 0 };
		cout << "Enter a number to test if it is prime : ";
		cin >> num;

		if (isPrime(num)) {
			cout << num << " is prime." << endl;
		}
		else {
			cout << num << " is not prime." << endl;
		}
		
		cout << "Try again (y/n)? ";
		
		cin >> again;
		again = toupper(again);  // both 'y' and 'Y' should work 
	}
	cout << endl;
	return 0;
}

bool isPrime(int num)
{
	if (num < 2) return false;
	for (int i = 2; i <= sqrt(num); i++) {
		if (num%i == 0) return false;
	}
	return true;
}

Test http://cpp.sh/3ayqj
Last edited on
closed account (48T7M4Gy)
Or avoid cmath/sqrt problems,
1
2
3
4
5
6
7
8
9
count = 2;
        while (count < input && count*count < input)
        {
            if (input % count == 0)
            {
                is_prime = false; // <-- only change if false
            }
            count++;
        }
Shorter?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main()
{
    char again = 'Y';
    do {
        std::cout << "Enter a number to test if it is prime: ";
        int num{};
        std::cin >> num;
        std::cout << num << " is " 
                  << [num]() -> const char* { 
                         for(int count{2}; count*count < num; count++) {
                            if(num % count == 0) {return "not prime.\n";}
                         }
                         return "prime.\n"; }()
                  << "\nTry again (y/n)? ";
        std::cin >> again;
    } while (again == 'Y' || again == 'y');
    return 0;
}

Ok, just kidding.
Sorry.
Topic archived. No new replies allowed.