Hi,(adsbygoogle = window.adsbygoogle || []).push({});

I'm new to programming and have written the following code to test for prime-ness, but it doesnt seem to work except for n = 3.

I think it may have something to do with my goto statement. Can anyone see a way of avoiding this or any other errors with the program?

Kind regards,Code (Text):

#include <iostream>

#include<math.h>

using namespace std;

int main() {

int n, i, is_prime;

//Assume # is prime untill proven otherwise

is_prime = true;

loop:

// get number

cout << "Enter a number and press ENTER (0 to exit): ";

cin >> n;

if (n == 0) {

return 0;

}

else {

//test for prime-ness.

i=2;

while (i <= sqrt(static_cast<double>(n))) {

if (n%i == 0)

cout << i << " is a factor of " << n << endl;

is_prime = false;

i++;

}

if (is_prime)

cout << "Number is Prime!" << endl;

else

cout << "Number is not prime!" << endl;

}

goto loop;

}

Peter

**Physics Forums - The Fusion of Science and Community**

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# Prime number test

Loading...

Similar Threads - Prime number test | Date |
---|---|

Prime Numbers (Eratosthenes) | Feb 26, 2017 |

Importance of prime numbers | Oct 15, 2014 |

C++ programming on prime numbers | Feb 18, 2014 |

Fastest prime number sieve | Nov 10, 2013 |

Boolean array to identify prime numbers - C++ | Feb 28, 2013 |

**Physics Forums - The Fusion of Science and Community**