Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // include necessary libraries
- // those are required for some types to work.
- #include <iostream>
- using namespace std;
- int main()
- {
- //declaring required variables.
- int num = 0;
- int c_prime = 0;
- //prompting user for inputs.
- cout << "Please enter an integer greater than 1 : " << endl;
- cin >> num;
- //extra line for spacing.
- cout << endl;
- //if the user happens to input a value less than 1, let him/her knows.
- //because this program was meant to find prime from 1.
- if(num<1){
- cout << "You will have to enter a number greater than 1, sorry.";
- }
- //goes only if the user input, num is greater than 1.
- while(num >1){
- //starts a for loop where d_num is assigned as num decreasing by 1 and as a decrementing value.
- for(int d_num = (num-1); d_num>1; d_num--){
- //assign the value of num to d_num.
- //where num will keep decreasing and
- //do a series of check to see if it's prime or not.
- num = d_num;
- //2 is a prime exception where it is the only even number.
- //we also know it is always prime.
- //this will output num if and when it becomes 2 before or after doing the loop
- //at least once.
- if(num ==2){
- cout << num << " is a prime number." << endl;
- }
- //c_prime is the remainder after dividing num by 2.
- //to check if it is divisible by 2.
- //there are not any prime numbers that is even except 2.
- c_prime = num%2;
- //this if loop runs if there is the remainder is not 0,
- //that means that this number,num might be a prime number.
- if(c_prime != 0){
- for(int d_num = (num-1); d_num >2; d_num--){
- //assign c_prime the value of the remainder of num divided by d_num, which is
- //a decreasing set of numbers starting from the value of num.
- c_prime = num%d_num;
- //check if the number, num has no remainder.
- //means that number is absolutely not a prime number.
- //and it will break the loop, starting program from top.
- if(c_prime == 0){
- break;
- }
- }
- //final check, checking if the number, num
- //has a remainder where c_prime will be greater than 0.
- //this means the num here is prime.
- if(c_prime !=0){
- //print out the prime number.
- cout << num << " is a prime number." << endl;
- //another case, if the value of c_prime at this point is 0,
- //it is absolutely not a prime number.
- //and this break the loop.
- }else if(c_prime == 0){
- break;
- }
- //break the loop so that it starts checking other numbers.
- break;
- }
- }
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment