Grupo
Funciones en C++
Ojetivo
1. Cree una función que reciba un entero y devuelva un valor booleano que indique si es primo.
2. Un número es primo si es mayor que 1 y divisible solo por 1 y por sí mismo.
3. Use un bucle para comprobar la divisibilidad del número desde 2 hasta la raíz cuadrada.
4. En la función principal, solicite al usuario un número y llame a la función para comprobar si es primo.
5. Muestre el mensaje correspondiente según el resultado de la función.
Implemente una función que devuelva si un número es primo.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the iostream library for input and output
#include <cmath> // Include cmath for using the square root function
using namespace std; // Use the standard namespace
// Function to check if a number is prime
bool isPrime(int number) {
// Prime numbers must be greater than 1
if (number <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}
// Check divisibility from 2 up to the square root of the number
for (int i = 2; i <= sqrt(number); i++) {
if (number % i == 0) {
return false; // If divisible by any number, it's not prime
}
}
return true; // If not divisible by any number, it's prime
}
// Main function - starting point of the program
int main() {
int num; // Variable to store the user's number
// Prompt the user to enter a number
cout << "Enter a number: ";
cin >> num; // Read the input number
// Call the isPrime function and display the result
if (isPrime(num)) {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}
return 0; // End of the program
}
Salida
Enter a number: 7
7 is a prime number.
Enter a number: 12
12 is not a prime number.
Comparte este ejercicio C++