Find the nearest prime number - MATLAB Cody - MATLAB Central

Problem 44384. Find the nearest prime number

Difficulty:Rate

Happy 5th birthday, Cody! Since 5 is a prime number, let's have some fun looking for other prime numbers.

Given a positive integer x, find the nearest prime number. Keep in mind that the nearest prime may be less than x.

Examples

nearestprime(5) = 5
nearestprime(36) = 37
nearestprime(200) = 199

NOTE: You may ignore cases in which two prime numbers are equally close to x. (e.g., x=12 --> 11 and 13 are both primes).

Solution Stats

31.39% Correct | 68.61% Incorrect
Last Solution submitted on Jun 16, 2025

Problem Comments

Solution Comments

Show comments
Why should you share code?
In a discussion on LInkedin about my recent blog post, Do these...
2
3

Problem Recent Solvers642

Suggested Problems

More from this Author44

Problem Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!