[go: up one dir, main page]

0% found this document useful (0 votes)
21 views4 pages

Ex 5

ex 5 KTLT hust

Uploaded by

Hải Long Văn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views4 pages

Ex 5

ex 5 KTLT hust

Uploaded by

Hải Long Văn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Ex 5: prime number check

1. requirement: write a function that accept a number as input and return True if
it is a prime number, and Flase otherwise
2. IPO

Input Process Output


Integer n>1 (int) Check divisibility from 2 If n is divisible by a
up to the square root of number from 2 up to the
n square root of n, return
True (bool)
If n is not divisible by a
number from 2 up to the
square root of n, return
False (bool)

3. flowchart
4. code
#include <stdio.h>
#include <stdbool.h>
#include <math.h>

// Function to check if a number is prime


bool isPrime(int n) {
// If the number is less than or equal to 1, it is not prime
if (n <= 1) {
return false;
}

// Check divisibility from 2 up to the square root of n


for (int i = 2; i <= sqrt(n); i++) {
// If n is divisible by i, it is not prime
if (n % i == 0) {
return false;
}
}

// If no divisors are found, n is prime


return true;
}

// Test the function


int main() {
int number;

// Prompt the user for a number


printf("Enter a number: ");
scanf("%d", &number);
// Check if the number is prime and print the result
if (isPrime(number)) {
printf("%d is a prime number.\n", number);
} else {
printf("%d is not a prime number.\n", number);
}

return 0;
}

You might also like