- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript: Finding nearest prime number greater or equal to sum of digits - JavaScript
We are required to write a JavaScript function that takes in a number, finds the sum of its digits and returns a prime number that is just greater than or equal to the sum.
Example
Following is the code −
const num = 56563; const digitSum = (num, sum = 0) => { if(num){ return digitSum(Math.floor(num / 10), sum + (num % 10)); } return sum; }; const isPrime = n => { if (n===1){ return false; }else if(n === 2){ return true; }else{ for(let x = 2; x < n; x++){ if(n % x === 0){ return false; } } return true; }; }; const nearestPrime = num => { let sum = digitSum(num); while(!isPrime(sum)){ sum++; }; return sum; }; console.log(nearestPrime(num));
Output
This will produce the following output in console −
29
- Related Articles
- Summing up digits and finding nearest prime in JavaScript
- Finding nearest prime to a specified number in JavaScript
- Prime digits sum of a number in JavaScript
- Nearest Prime to a number - JavaScript
- Finding nearest Gapful number in JavaScript
- Select equal or nearest greater number from table in MySQL
- Finding product of Number digits in JavaScript
- Finding all possible prime pairs that sum upto input number using JavaScript
- Finding the nth prime number in JavaScript
- Finding next prime number to a given number using JavaScript
- Getting equal or greater than number from the list of numbers in JavaScript
- Finding n subarrays with equal sum in JavaScript
- Finding points nearest to origin in JavaScript
- Finding the largest prime factor of a number in JavaScript
- How to get the smallest integer greater than or equal to a number in JavaScript?

Advertisements