etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Program to find prime number

In this post, you will learn programs in different languages to print Prime numbers.

A prime number is a whole number greater than 1, whose only factors are 1 and itself, like -2, 3, 5, 7, 11 etc. For example, 17 is a prime number because it is only divisible by 1 and 17, on the other hand, 18 is not a prime number because it is divisible by 2, 3, 6, 9 and number itself.



Java print prime numbers from 1 to 20 using for loop

Here, we have used for loop to get prime numbers from 1 to 20. We loop over the number range (1 to 20) and check whether the number is prime or not. The for loop iterates from i=0 to i=given number, if the remainder of i/num = 0 then increases the count by 1. After all the iterations, if counter=2, then that number is a prime number.

public class CheckPrimeNumbers
{
    public static void main (String[] args)
    {		
       int i =0;
       int num =0;
       
       String  prime_numbers = "";

       for (i = 1; i <= 20; i++)         
       { 		  	  
          int counter=0; 	  
          for(num =i; num>=1; num--)
    	  {
             if(i%num==0)
    	     {
     		    counter = counter + 1;
    	     }
    	  }
    	  if (counter ==2)
    	  {
    	     prime_numbers = prime_numbers + i + " ";
    	  }	
       }	
       System.out.println("Prime Numbers between 1 and 20 :");
       System.out.println(prime_numbers);
    }
}
Output of the above code:
Prime Numbers between 1 and 20 :
2 3 5 7 11 13 17 19 




PHP Prime Number Program using While Loop

The following PHP code prints a list of prime numbers between 1 and 100 (that is, numbers not divisible by something other than 1 or the number itself) using a while loop.

<?php  
	$limit = 30;
	$init = 2;
	
	while(TRUE)
	{
		$div = 2;
		if($init > $limit) 
		{
			break;
		}
		while(TRUE)
		{
			if($div > sqrt($init))
			{
				echo $init."  ";
				break;
			}
			if($init % $div == 0) 
			{
				break;
			}
			$div = $div + 1;
		}
		$init = $init + 1;
	}
?>
Output of the above code:
2  3  5  7  11  13  17  19  23  29  




Python Program to print Prime Numbers between interval

Here is the Python program to print prime numbers between given interval using for loop. Numbers less than or equal to 1 are not prime numbers. That's why, we have started the range from 1.

for num in range(1, 50):  
   if num > 1:  
       for i in range(2,num):  
           if (num % i) == 0:  
               break  
       else:  
           print(num)  
Output of the above code:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47




C++ program to print Prime Number

The given C++ program takes the range and finds all the prime numbers between the range and also prints the number of prime numbers.

#include<iostream>
using namespace std;

//function to check for prime number
void prime(int num)
{
    int div=0;
    
    //checking for number of divisor
    for(int i=1;i<=num;i++)
    {
       if(num%i==0)
          div++;                
    }
    
    if(div==2)
      cout<<num<<endl;
}
int main()
{
    cout<<"Please enter range: ";    
    int min, max;
    
    cin>>min>>max;
    cout<<"Prime numbers between "<<min<<" and "<<max<<" are:"<<endl;
    
    //finding prime numbers in the given range
    for(int i=min;i<=max;i++)
            prime(i);
    return 0;
}
Output of the above code:
Please enter range: 20 40
Prime numbers between 20 and 40 are:
23
29
31
37




C Program to Find Prime Numbers in a given Range

The given C program takes the range and finds all the prime numbers between the range and also prints the number of prime numbers.

#include <stdio.h>

int main() {
   int min, max, i, flag;
   printf("Please enter range: ");
   scanf("%d %d", &min, &max);
   printf("Prime numbers between %d and %d are: ", min, max);

   // iteration until low is not equal to high
   while (min < max) {
      flag = 0;

      // ignore numbers less than 2
      if (min <= 1) {
         ++min;
         continue;
      }

      // if low is a non-prime number, flag will be 1
      for (i = 2; i <= min / 2; ++i) {
         if (min % i == 0) {
            flag = 1;
            break;
         }
      }

      if (flag == 0)
         printf("%d ", min);

      ++min;
   }
   return 0;
}
Output of the above code:
Please enter range: 50 70
Prime numbers between 50 and 70 are: 53 59 61 67 




Related Articles

Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert array to list Python
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Check if two strings are anagrams Python
Python program to add two numbers
Print new line python
Prime factors of a number in c
Armstrong number program in c
Write a program to check leap year in c
C program to find area of rectangle
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to convert Decimal to Octal
C program to convert decimal to binary
C program to check whether a number is even or odd




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple pagination in PHP with MySQL
-----------------
How to generate QR Code in PHP
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
PHP MYSQL Advanced Search Feature
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
jQuery File upload progress bar with file size validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
To check whether a year is a leap year or not in php
-----------------
Php file based authentication
-----------------
Simple File Upload Script in PHP
-----------------
Simple PHP File Cache
-----------------
PHP User Authentication by IP Address
-----------------
Calculate the distance between two locations using PHP
-----------------
PHP Secure User Registration with Login/logout
-----------------
Polling system using PHP, Ajax and MySql
-----------------
How to print specific part of a web page in javascript
-----------------
Detect Mobile Devices in PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
Simple way to send SMTP mail using Node.js
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Google Street View API Example
-----------------
PHP Sending HTML form data to an Email
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
PHP Programming Error Types
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
PHP Getting Document of Remote Address
-----------------
How to display PDF file in web page from Database in PHP
-----------------
File Upload Validation in PHP
-----------------
PHP FTP Connection and File Handling
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.