Prime Number Code

Can anybody help me write this short code? I've only written a couple programs so far but with this assignment I don't really know where to start. I was already fuzzy on how a loop works to begin with and now it's getting a little more complex. I know that it isn't a particularly long code, so I would appreciate the help.

Prime Numbers. Write a program that reads in an integer that is greater than 2 (let's call it k) and finds and prints all of the prime numbers between 3 and k.

One way to solve this problem is to use a doubly nested loop. The outer loop can iterate from 3 to k while the inner loop checks to see if the counter value for the outer loop is prime. One way to see if number n is prime is to loop from 2 to n-1 and if any of these numbers evenly divides n, then n cannot be prime. If none of the values from 2 to n-1 evenly divides !n, then n must be prime.
What you want to do is make two loops; one (outside loop) being for all numbers between 3 and the number given by the user while the other (inside loop) takes that number and checks to see if it's prime.

Outside loop: 3 to k
Inside loop 2 to (k-1)

Luckily, there is a way to check if something is able to divide evenly (hint: % --> k%n == 0). You would want to do this for each number in the inner loop to see if it divides evenly (look at hint). If it does, automatically say it's not prime, otherwise it is.
Thank you but I'm still not sure where to start. I don't mean to sound useless but do you think you could write a sample so I could understand better?
Here, I'll write some pseudo code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool isprime = true; //used to determine if number is prime or not
for(from 3 to k)
{
	for(from 2 to k-1)
	{
		if(if k%n == 0)
		{
			isprime = false;
			break out of code;
		}
		if (isprime)
		{
			print out the number
		}
		isprime = true; //reset isprime for next use
	}
}


This is the basic structure of how it should be done
closed account (1CfG1hU5)
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
#include <stdio.h>

int prime(int n);

int main()
{
	int i, n;

	n = 1000;
	for (i=2; i<=n; i++)
		if (prime(i))
             printf("%d ", i);

return 0;

}

int prime(int n)
{
	int i;

	if (n % 2 == 0)
		return (n==2);
	if (n % 3 == 0)
		return (n==3);
	if (n % 5 == 0)
		return (n==5);
	for (i=7; i*i <= n; i+=2)
		if (n % i == 0)
			return 0;
	return 1;
}


can get more primes by changing the value of n in main func
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
bool prime (int number);
using namespace std;

int main ()
{
 	for ( int i = 2; i < 100; i++ )
 		{
 			if ( prime( i ) )  
   			cout << i << endl;  
 		}
	return 0;
}

bool prime (int number)
{
 	for ( int i = 2; i < number; i++)
 		{  
  			if ( number % i == 0 )  
    		return false;  //not prime
		 }  
	return true; //prime
}
Topic archived. No new replies allowed.