Check Given Number Prime or Not

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 37 - Check Given Number Prime or Not

To check whether a given number is prime or not, you can write a C++ program that takes an integer input from the user and checks for its divisibility by any numbers other than 1 and itself. A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.

Here's a C++ program to check if a given number is prime or not:

cppCopy code

#include <iostream> bool isPrime(int number) {    if (number <= 1) {        return false;    }    for (int i = 2; i * i <= number; i++) {        if (number % i == 0) {            return false;        }    }    return true; } int main() {    int number;    std::cout << "Enter a positive integer: ";    std::cin >> number;    if (isPrime(number)) {        std::cout << number << " is a prime number." << std::endl;    } else {        std::cout << number << " is not a prime number." << std::endl;    }    return 0; }

Example output:

lessCopy code

Enter a positive integer: 7 7 is a prime number.

lessCopy code

Enter a positive integer: 10 10 is not a prime number.

In the program, we define a separate function isPrime that takes an integer as an argument and returns a boolean value. This function checks whether the number is prime or not by iterating from 2 up to the square root of the number. If the number is divisible by any value in this range, it returns false; otherwise, it returns true. We handle the special cases of numbers less than or equal to 1, as they are not considered prime.

Feel free to run this program with different positive integers to check if they are prime or not.

5. Week2 - Assignments

Comments: 2

profile
@mk.info.work
17-Feb-2024, 10:20 PM

SCIAKU Team please upload 1st video of TREE please please please, please

profile
@na3744
23-Feb-2024, 02:52 AM

I bought this course, it worth it!

profile
@mk.info.work
15-Nov-2023, 10:25 PM

Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it

profile
@sciaku1
11-Jan-2024, 03:23 PM

Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?