c++ - "Prime or not" program -


i stuck on simple program in c++, let user know number she/he have entered prime or not, but, because of reason, works fine during first loop things go fishy during second. more happy if ?

#include <iostream> using namespace std;  int main(int argc, const char* argv[]) {     int number1 = 5;     int number;     int = 0;      while (number1 == 5)     {         int b = 1;         cout << "enter number , we'll tell if it's prime or not: ";         cin >> number;          while (a <= number)         {             a++;             if (number % == 0)                 b++;         }          if (b == 3)             cout << "your number prime" << endl;         else             cout << "your number not prime" << endl;     } } 

the several problems program.

the first 1 loop starting statement

while (number1 == 5) 

is infinite because number1 not changed within loop.

the second 1 must initialize variable a 0 within loop. , should defined within loop because not used outside loop. same valid variable number.

take account number prime if divisble 1 , (except number 1). set variable b 0 , compare 2. more clear compare 3.

the program can following way

#include <iostream>  int main() {     while ( true )     {         std::cout << "enter number , we'll tell if it's prime or not (0-exit): ";          unsigned int number = 0;         std::cin >> number;          if ( number == 0 ) break;          unsigned int n = 0;         unsigned int divisor = 0;          while ( divisor++ < number )         {             if ( number % divisor == 0 ) n++;         }          if ( n == 2 )             std::cout << "your number prime" << std::endl;         else             std::cout << "your number not prime" << std::endl;     } } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -