Prime number | homework

Oct 27, 2015 at 9:44am
Hola, so recently I started my programming course and I am not good at it yet.
So let's get into the main problem, I have to make a program: "user inserts two numbers "m" & "n" (int m, n;)and program has to find all the prime numbers between "m" & "n"

So I am not sure how to do it, should I use some kind of an array or what, any help would be appriciated!

With much thanks
Oct 27, 2015 at 9:48am

Well, assuming you know how to check for a prime number then a loop would be good here, create a loop from m to n and inside that loop check if the current loop position is a prime number and if it is then display it.

Edit: Here is a link to help you out: http://www.cplusplus.com/doc/tutorial/control/
Last edited on Oct 27, 2015 at 9:49am
Oct 27, 2015 at 9:55am
Thanks, btw, is an array needed to check the current loop position?
Oct 27, 2015 at 9:59am
No, its not mandatory

1
2
3
4
5
for(int i=m;i<=n;i++)
{
cout<<i;
checkprime();
}


the output of this would be somewhat like this


5 is a prime
6 is nor a prime
7 is a prime
8 is not a prime


as you can see by checking the value of i only we can check the current loop position
Last edited on Oct 27, 2015 at 10:00am
Oct 27, 2015 at 10:05am

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
#include <iostream>

int main()
{

	// these are just dummy variables, in 
	// your code you would be asking the 
	// user what numbers.
	int m = 10;
	int n = 20;

	// for (initialization; condition; increase) statement;
	// so here I initialise number to m, the condition tells
	// it to loop while number is below or equal to n, and
	// lastly we say number++ to increase each time we loop
	for (int number = m; number <= n; number++)
	{
		// we loop and each time we do, the
		// number variable will increase by
		// 1

		// lets test this by displaying it.
		std::cout << number << std::endl;

	}

	return 0;
}

10
11
12
13
14
15
16
17
18
19
20
Oct 27, 2015 at 10:05am
Hmm, mkay and where should I put the prime number checking code?
Oct 27, 2015 at 10:05am
closed account (48T7M4Gy)
If you use the sieve of Eratosthenes approach an array is useful

https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Oct 27, 2015 at 10:13am

Hmm, mkay and where should I put the prime number checking code?

Where would you feel is the right logical place to test if number is a prime number?
Oct 27, 2015 at 10:19am
In the loop condition probably, Ty a lot guys, gona try it at home, and yea if someone have other ideas write it down, cheers
Oct 27, 2015 at 10:23am

Yes, inside the Loop, you are needing to check the value of number, good luck :)
Topic archived. No new replies allowed.