# Thread: Small program, PRIME/ PERFECT SQUAREs

1. ## Small program, PRIME/ PERFECT SQUAREs

I wrote this code for finding out if a number entered is a prime number or a perfect square. It only works if the number entered is a perfect square already. all else totally fails.

0----------------------------------

#include <iostream>
#include <iomanip>

void main()

{

int num;
bool prime = true;

cout << "Enter a number" << endl;
cin >> num;

for (int p=1; p < num; p++)
{
if ( num % p == 0 )
{

prime = false;

if (p * p == num )
{
cout << num << " is a perfect square. Its square root is " << p << endl<<endl;
}
}

}

if ( prime )
cout << num << " is a prime number."<<endl<<endl;

}

---------END

Any ideas?

2. i would recommend placing this in your other thread. also, listen to not using void main. do a search if you would like to know why...

3. lol, really your advice has been well taken, as I have haerd of the horror stories reguarding it. however, our teacher prefers us to use void main as of right now. i think he wants us to learn a lesson or something later on.

4. Originally posted by thynksheraze
our teacher prefers us to use void main as of right now.
Code:
```/* your headers here */

#ifdef MY_TEACHER_IS_A_MORON
void
#else
int
#endif
main ( )
{
/* your code here */

#ifndef MY_TEACHER_IS_A_MORON
return 0;
#endif
}```
Then, when you turn in your home work, make the first line of your program:

#define MY_TEACHER_IS_A_MORON

Quzah.

5. Originally posted by quzah
Code:
```/* your headers here */

#ifdef MY_TEACHER_IS_A_MORON
void
#else
int
#endif
main ( )
{
/* your code here */

#ifndef MY_TEACHER_IS_A_MORON
return 0;
#endif
}```
Then, when you turn in your home work, make the first line of your program:

#define MY_TEACHER_IS_A_MORON

Quzah.
lol. talk about not getting on his teacher's good side. but seriously, just use it. my teacher somewhat teaches void main, she knows it is supposed to be int, but...i use int anyways.

6. The problem is that the loop is starting from 1..

WHat is
10%1
40%1
7%1

see the problem..... Start the loop from 2.... And i would recomend that you stop the loop at num/2 that is.

instead of for (int p=1; p < num; p++) use for (int p=1; p < num/2; p++)

Since there is no need to run the loop after that...
If you want to find say wheather 7 is prime..

is 7 divisible by 2 ---no
7 divisible by 3 ---no
you dont need to do it for 4 ,5 and other numbers because multiplying it by 2 will give a value greater than 7...

7. Or even better, instead of stopping at num/2 you could stop at sqrt(num) since any number checked after that would have to be multiplied by a lower number, and you've already checked all the lower numbers.

Popular pages Recent additions