?
Solved

Nearest prime number

Posted on 1999-12-29
4
Medium Priority
?
1,983 Views
Last Modified: 2009-05-28
How to write a C program to find a prime number nearest to an input interger num.
0
Comment
Question by:wewe
  • 2
4 Comments
 
LVL 10

Expert Comment

by:rbr
ID: 2314186
Pls give more info. How many digits, what kind of algorithm to you want, is it a homework?
0
 
LVL 2

Accepted Solution

by:
yairy earned 40 total points
ID: 2314216
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
 
LVL 2

Expert Comment

by:yairy
ID: 2314217
>> to gap between TWO primes...
0
 

Author Comment

by:wewe
ID: 2314308
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

Featured Post

Live webcast with Pinal Dave

Pinal Dave will teach you tricks to help identify the real root cause of database problems rather than red herrings. Attendees will learn scripts that they can use in their environment to immediately figure out their performance Blame Shifters and fix them quickly.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
Suggested Courses

588 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question