In: Computer Science
A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided evenly by 1, 2, 3, and 6. Write a Boolean function named is_prime which takes an integer as an argument and returns true if the argument is a prime number, or false otherwise. Use the function in a program that displays all of the prime numbers from 1 to 100. The program should have a loop that calls the is_prime function.
c++
#include <iostream>
int is_prime (int);
int main() {
bool isPrime;
int count;
std::cout << "Enter the value of n: ";
std::cin >> count;
for(int n = 2; n < count; n++)
{
// isPrime will be true for prime numbers
isPrime = is_prime (n);
if(isPrime == true)
std::cout<< n <<" ";
}
return 0;
}
// Function that checks whether n is prime or not
int is_prime (int n) {
bool isPrime = true;
for(int i = 2; i <= n/2; i++) {
if (n%i == 0)
{
isPrime = false;
break;
}
}
return isPrime;
}
output -
java
import java.util.Scanner;
class Main {
// Function that checks whether n is prime or not
public static boolean is_prime (int num) {
int temp;
boolean isPrime=true;
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
return isPrime;
}
public static void main(String[] args) {
boolean isPrime = false;
Scanner scan= new Scanner(System.in);
System.out.print("Enter any number:");
//capture the input in an integer
int count = scan.nextInt();
scan.close();
for(int n = 2; n < count; n++)
{
// isPrime will be true for prime numbers
isPrime = is_prime(n);
if(isPrime == true)
System.out.print(n + " ");
}
}
}
output
python
print('Enter number')
num = int(input())
print('Prime numbers between 1 and 100 are:')
for possiblePrime in range(2, num):
# Assume number is prime until shown it is not.
is_prime = True
for num in range(2, possiblePrime):
if possiblePrime % num == 0:
is_prime = False
if is_prime :
print(possiblePrime)
output