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

2 Comments

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

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

@na3744
na3744 Feb 23, 2024 at 2:52 AM

I bought this course, it worth it!

@mk.info.work
mk.info.work Nov 15, 2023 at 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

@sciaku1
sciaku1 Jan 11, 2024 at 3: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 About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support