Prime Numbers Between 1-1000

Monday, September 09, 2013 7 Comments A+ a-

C++ program to find prime numbers between 1 to 1000


Problem:
Write a C++ program which prints all the prime numbers from 1-1000. 

Prime numbers are numbers greater than 1 and which has 1 and the number itself as positive factors or divisors. It doesn't have a positive factor or divisors other than 1 and the number itself.

Let's take 5 for example:
1 and 5 (the number itself) can evenly divide 5 so they are factors of 5.
2, 3, 4 are cannot evenly divide 5 so they are not factors of 5.
Therefore, 5 is a Prime Number.

This is a program which shows the Prime Numbers from 1-1000.


/*
Prime Numbers (from 1 - 1000)
*/
#include <iostream>

using namespace std;

int main(void)
{
 int num,i,countFactors;
 char hang;

 cout << "Prime numbers (1-1000) : " << endl;

 for (num = 1; num <= 1000; num++)
 {
  countFactors = 0;

  for (i = 2; i <= num; i++)
  {
   //if a factor exists from 2 up to the number, count Factors
   if (num % i == 0)
   {
    countFactors++;    
   }
  }

  //a prime number has only itself as a factor
  if (countFactors == 1)
  {
   cout << num << ", ";
  }
 }

 //to let console stay
 cin >> hang;

 return 0;
}

7 comments

Write comments
November 10, 2013 at 1:32 AM delete This comment has been removed by the author.
avatar
Vinster
AUTHOR
November 13, 2013 at 1:15 AM delete

Hope this helped you!..thanks for visiting! :)

Reply
avatar
April 15, 2016 at 8:27 AM delete

Programming is very interesting and creative thing if you do it with love. Your blog code helps a lot to beginners to learn programming from basic to advance level. I really love this blog because I learn a lot from here and this process is still continuing.
Love from Pro Programmer

Reply
avatar
Jaspal Bhatti
AUTHOR
December 14, 2016 at 11:50 AM delete

Aatka prasansa kre layak ghalo nhi btaye he Tay toh ukhar aysan tariff karths ki jano mano bhut bade ..mahapurush he

Reply
avatar
Unknown
AUTHOR
February 11, 2017 at 4:52 AM delete

help number between 1-1000 help tell me answer

Reply
avatar
Prime Numbers
AUTHOR
July 29, 2017 at 1:54 AM delete

The prime number distribution sequence can only provide accurate results if multiple counting of equal terms is averted.

Reply
avatar
Hitesh Kumar
AUTHOR
November 15, 2017 at 7:38 PM delete

This code is frequently ask in any examination Check Number is Prime or not in C++ is very simple and easy to write. Using for loop and if else we can write this code. Your code is very simple and easy to understand. Thanks for sharing this article.

Reply
avatar