• C

Nearest prime number

How to write a C program to find a prime number nearest to an input interger num.
weweAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

rbrCommented:
Pls give more info. How many digits, what kind of algorithm to you want, is it a homework?
0
yairyCommented:
The gap between to prime numbers
near the number N is in average Log*N.

It meen you should just take from the number one more, one less, two more, two less and so on and check
(n+-1, n+-2, n+-3 ...)

Very fast You will find a prime !

How to check if its a prime ?

check all numbers from 2..root(n)
if noone divides it - its a prime.

bool IsPrime(int n)
{
      int i;
      bool IsAPrime=true;
      for (i=2; i<=sqrt(n); i++)
      {
            if (n%i==0)
                  IsAPrime=false;
      }

      return IsAPrime;
}

Yair
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
yairyCommented:
>> to gap between TWO primes...
0
weweAuthor Commented:
To:rbr
 Yes!It is my homework.
 I have to write 2 function:
"isPrime" ~ find prime number,if the num is not a prime then return 0; else return 1.
"findPrime" ~ accept an interger and return a prime number which is nearest to it or the same as the given num.
 The findPrime function should call the isPrime function to find the prime number.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.