Function finds all prime numbers between two user inputted numbers

I've been stuck on this problem for awhile now. Can someone help me out?

http://gyazo.com/34082be87f7c655d562b02ea5ad7bc0c

And this is my code. I feel like I'm close but not sure.
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
44
   int prim(int x, int y,int i, int j){
							
							
		 for (i=2; x>0;i++ ) {
			 bool isPrime;
			 for (j=2; j<i ; j++) {
 				 if (i%j==0) {
					 isPrime = false;
				 }
				 }
			 if (isPrime) {
				 --x;
				 return i;
			 }
		 }
		 
	 }
		 
		

		
int	main()
	{	
			
		int a;
		int b;
		int c=2;
		int d=2;
 		int x;
			
			
			
		cout << "Enter a number" <<endl;
		cin>>a;
		cout << "Enter a number" <<endl;
		cin>>b;
			
		x=prim(a,b,c,d);
			
		cout << x <<endl;
			
			
		return 0;
	}
Last edited on
I made a couple of changes to your code. I used a void function instead of int because there are cases (perhaps the majority) where there are more than 1 prime number between the two numbers the user inputs. I tried to add comments where I made some changes

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
44
45
46
47
48
  #include <iostream>
  #include <cmath>
  
  using namespace std;
  
   void prim(int x, int y) // void function and removed the two extra parameters that were only used in the for loops
   {
							
							
		bool isPrime;
		for (int n =x;n<=y;n++) // loops between the two numbers the user inputs
		{
			isPrime = true; //set isPrime as true unless it is not prime, which you find with the next loop
		
			for (int i=2;i<n-1;i++) // checks for primes within the previous loop
			{
				if (n%i==0)
				{
					isPrime = false;
				}		
			}
			if (isPrime)
			{
				cout << n << endl; //replaces your return from the int function
			}
		}
		 
	}
		 
		

		
int	main()
	{	
			
		int a;
		int b; // removed additional variables only used in for loops in function		
			
		cout << "Enter a number" <<endl;
		cin>>a;
		cout << "Enter a number" <<endl;
		cin>>b;
			
		prim(a,b); // function call
			
			
		return 0;
	}
Topic archived. No new replies allowed.