#include<iostream>
using namespace std;
int main()
{
int a,d;
cout<<"Enter a integer to check it is prime or not :";
cin>>a;
d=2;
while(a%d!=0)
{
d++;
}
if(a==d)
{
cout<<"\n the given number id prime ";
}

else
  cout<<"\n the given number is not a prime number ;"

  return 0;
  }

Recommended Answers

All 2 Replies

Not a good approach. Set up a Sieve of Aristhostenes array (I usually hard code a 10K array) for initial lookup - remembering that a%2 == 0 indicates the number is even, hence not prime. You only have to deal with odd numbers. If the number you are looking at 'a' is bigger than the 10K array limit, then you can easily find with a recursive algorithm that will minimize the number of divisions you need to perform. This is a pretty good article on the subject: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

I coded the solution to this many years ago and could determine if a number was prime up to 15 digits on an old 80286 / 80287 processor computer in a few milliseconds. With current infinite precision libraries such as Boost these days, you can go to any number of digits in a very short time.

commented: Some folk find it odd to use prior works. I think this makes us even. +10

I coded the solution to this many years ago and could determine if a number was prime up to 15 digits on an old 80286 / 80287 processor computer in a few milliseconds.

Any chance you stilll have that code? Did you code it in C/C++? I would be interested in seeing the code. That seems remarkably fast for that processor or even a modern processor. My prime number generators certainly never worked that fast. I'm open to that being due to me not coding it correctly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.