/* ************************************************************************** * Program name : 032_Prime_number(Method_2) (Version 1.00) * * Author : Duck Wong * * Language : C / C++ * * Compiler : Boodshed Dec-C++ compiler Ver 3.95 * * Computer : PII350 * * O/S : Windows 98 * ************************************************************************** * Version 1.00 : 2000/06/13 - first version * ************************************************************************** * Description : (a) Input the lower limit * * (b) Input the upper limit * * (c) Find all prime number within the range * * (d) Try again ? * ************************************************************************** */ #include #include #include void findprime(int Lower, int Upper) { int Index_1,Index_2, Count; char Status; Count = 0; // Note (1) if (Lower==1 || Lower==2) // Note (2) { Lower = 3; Count++; cout << 2 << "\t"; } if (Lower % 2 == 0) Lower++; // Note (3) for (Index_1=Lower; Index_1<=Upper; Index_1 += 2) // Note (4) { Status = 'Y'; // Note (5) for (Index_2=3; Index_2<=ceil(sqrt(Index_1)); Index_2 += 2) // Note (4) if ((Index_1 % Index_2)== 0) // Note (6) { Status='N'; break; } if (Status=='Y') { Count++; cout << Index_1 << "\t"; } } cout << "\nThere are " << Count << " prime numbers in the range."; } int main() { // part 1 : declaration int Upper, Lower; char Again; // part 2 do { // part 2a : input an integer do { cout << "\nThis program can find all prime numbers within" << "\na range of integer numbers.\n" << "\nPlease enter the lower and upper limits : "; cin >> Lower >> Upper; } while (Lower<=0 || Upper<=0 || Upper < Lower ); // part 2b : Call the function to find all the prome numbers cout << "\nThe prime number is (are) : \n"; findprime(Lower,Upper); cout << "\n"; // part 2c : Try another range ? cout << "\a\n\nTry another range (Y/N) : "; cin >> Again; } while (Again=='Y' || Again=='y'); cout << "\n\n" << endl; system("PAUSE"); return 0; } /* Notes (1) The variable "Count" is used to count the number of prime number in the range. The value of Count is set to zero each time before checking the numbers in the range. (2) When the "Lower" limit is "1" or "2", the computer will asjust it to "3" , add 1 to "Count" and output the number "2" to the screen. (3) The statement "if (Lower % 2 == 0) Lower++;" make sure the first number (Lower) to be check is an odd number since all even numbers are not prime number. Then the for loop check all the odd numbers in thr range as the counter "Index_1" is incrmented by "2". (4) The counter "Index_1" and "Index_2" are incrmented by "2" since the program needs to check all odd numbers only. (5) The variable "Status" is used to as a flag to represent the number is not prime number ('N') or a prime number ('Y'). (6) If Index_2 is a divisor of Index_1 , then Index_1 is not prime number. */