0
Can u help with this simple code!!
You are given an integer N. You need to print the series of all prime numbers till N. Input Format The first and only line of the input contains a single integer N denoting the number till where you need to find the series of prime number. Output Format Print the desired output in single line separated by spaces. Constraints 1<=N<=1000 SAMPLE INPUT Â 9 SAMPLE OUTPUT Â 2 3 5 7
3 Answers
+ 3
We will be very happy to help you, but first you should show us what you have done so far. At least I don't enjoy doing ALL the work for someone else. You can simply link your project here so we can see it.
+ 1
Not quite a project link, but okay.
First of all, your for-loop is incorrect. Basically, what we want to do is to iterate through all numbers from the first prime number (2) to N. Syntax would be:
for ( int x = 2; x < N; ++x ) {}
And now we have to test for each x if it is really a prime number. We can do so by testing if it has any other divisors besides 1 and itself. This would be what happens inside the for-loop:
bool isPrime = true; // indicator
for ( int i = 2; i < x / 2; ++i ) {
if ( x % i == 0 ) {
isPrime = false;
}
}
if ( isPrime == true ) {
std::cout << ' ' << x;
}
Here, we simply iterate through the numbers from 2 to half of x, and if a number is a perfect divisor of x (the remainder is 0 in that case), it is not a prime. If isPrime is still true after the loop is done, x must be prime, therefore we print it.
Here is a full example, with some optimizations for less loop iterations:
https://code.sololearn.com/c9L97nf3oAZW/?ref=app
0
int N , x ;
Cin >> N;
For (x=N ; 0<=N=<10 ; x++ ){
Cout << x << endl;
}
Shadow this what I have done so far,this my approach.