Help Please before i go crazy!!!!
Hi there can you help me understand what is happening in this program or in other words try and explain the logic of it to me, i can understand the program but for one line.
This is the line: for(j=2; j <= i/2; j++)
Like is this for statement a loop or what is it. I just don't get the j<=i/2 bit can some please expalin this bit to me, before i go crazy.
The program basically is to find and output prime numbers between 1 - 100.
#include <iostream>
using namespace std;
int main() {
int i, j;
bool isprime;
for(i=1; i < 100; i++)
{
isprime = true;
// see if the number is evenly divisible
for(j=2; j <= i/2; j++)
// if it is, then it is not prime
if((i%j) == 0)
isprime = false;
if(isprime)
cout << i << " is prime.\n";
}
return 0;
}
Many Thanks
almul
Re: Help Please before i go crazy!!!!
Use code tags like this:
Code:
#include <iostream>
using namespace std;
int main()
{
int i, j;
bool isprime;
for(i=1; i < 100; i++)
{
isprime = true;
// see if the number is evenly divisible
for(j=2; j <= i/2; j++)
// if it is, then it is not prime
if((i%j) == 0)
isprime = false;
if(isprime)
cout << i << " is prime.\n";
}
return 0;
}
Would it make more sense to you like this
Code:
#include <iostream>
using namespace std;
int main()
{
int i, j;
bool isprime;
for(i=1; i < 100; i++)
{
isprime = true;
// see if the number is evenly divisible
int limit = i / 2;
for(j=2; j <= limit; j++)
// if it is, then it is not prime
if((i%j) == 0)
isprime = false;
if(isprime)
cout << i << " is prime.\n";
}
return 0;
}
It's the same thing
Re: Help Please before i go crazy!!!!
Thanks but what does the: "i/2" bit actually mean. Thats what im having trouble understanding.
Also is the second for statement an actually loop???
Can someone please explain.
Thanks
Re: Help Please before i go crazy!!!!
Quote:
Originally Posted by
almul
Thanks but what does the: "i/2" bit actually mean. Thats what im having trouble understanding. Can someone please explain.
Just like kindergarten arithmetic...
For integers:
1 / 2 = 0
2 / 2 = 1
3 / 2 = 1
4 / 2 = 2
5 / 2 = 2
6 / 2 = 3
7 / 2 = 3
8 / 2 = 4
etc.
Re: Help Please before i go crazy!!!!
Ok got that bit sorted now for the second for statement. Is this 2nd for statement a loop if it is then where are its curley brackets?
Thanks
Re: Help Please before i go crazy!!!!
As supplied, this code is equivilent to:
Code:
#include <iostream>
using namespace std;
int main()
{
int i, j;
bool isprime;
for(i=1; i < 100; i++)
{
isprime = true;
// see if the number is evenly divisible
for(j=2; j <= i/2; j++) if((i%j) == 0) isprime = false;
if(isprime) cout << i << " is prime.\n";
}
return 0;
}