Javascript - Too much recursion - javascript

So, I'm making a function which solves a 4x4 sudoku. It takes in a 2D array and all the empty fields are replaced with 0s. With the isSafe function I'm trying to split the checks into multiple functions that way that it's easier to read. Althought I've tried some forms of avoiding the too much recursion as to implement a certant amount of checks etc.
I've tried setting maxIterations, tried returning false, returning null... Really was out of ideas.
I've noticed that it crashes quite fast, It can only solve a few numbers and then the error occurs. If anyone has a more efficent way please comment.
function solverFor4x4(grid) {
let number = generateRandom(1, 5, [0, 5]);
if (!number) {
return;
}
console.log(number)
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if(grid[i][j] == 0 && isSafe(grid, number, i, j)) {
grid[i][j] = number;
}
}
}
showSolution(grid);
}
function isSafe(grid, number, i, j) {
if(isSafeRow(grid, number, i, j) && isSafeColumn(grid, number, i, j) && isSafeArea(grid, number, i, j)) {
return true;
}
}
function isSafeRow(grid, number, i, j) {
if (grid[i].includes(number)) {
solverFor4x4(grid);
} else {
return true;
}
}
function isSafeColumn(grid, number, i, j) {
let array = [];
for (let i = 0; i < grid.length; i++) {
if(grid[i][j] == number) {
solverFor4x4(grid);
} else {
array.push(grid[i][j]);
}
}
if(array.includes(number)) {
solverFor4x4(grid);
} else {
return true;
}
}
function isSafeArea(grid, number, i, j) {
return true;
}
function generateRandom(min, max, exclude) {
let random;
let counter = 0;
const maxIterations = 100;
while (!random && counter < maxIterations) {
const x = Math.floor(Math.random() * (max - min + 1)) + min;
if (exclude.indexOf(x) === -1) {
random = x;
}
counter++;
}
return random || null;
}
EDIT: Forgot to place the code, sorry.

Here's the updated code:
function solverFor4x4(grid) {
let number = generateRandom(1, 5, [0, 5]);
if (!number) {
return;
}
console.log(number)
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if(grid[i][j] == 0 && isSafe(grid, number, i, j)) {
grid[i][j] = number;
}
}
}
showSolution(grid);
}
function isSafe(grid, number, i, j) {
if(isSafeRow(grid, number, i, j) && isSafeColumn(grid, number, i, j) && isSafeArea(grid, number, i, j)) {
return true;
} else {
return false;
}
}
function isSafeRow(grid, number, i, j) {
if (grid[i].includes(number)) {
return false;
} else {
return true;
}
}
function isSafeColumn(grid, number, i, j) {
let array = [];
for (let i = 0; i < grid.length; i++) {
if(grid[i][j] == number) {
return false;
} else {
array.push(grid[i][j]);
}
}
if(array.includes(number)) {
return false;
} else {
return true;
}
}
function isSafeArea(grid, number, i, j) {
return true;
}
function generateRandom(min, max, exclude) {
let random;
let counter = 0;
const maxIterations = 100;
while (!random && counter < maxIterations) {
const x = Math.floor(Math.random() * (max - min + 1)) + min;
if (exclude.indexOf(x) === -1) {
random = x;
}
counter++;
}
return random || null;
}
If not working try this:
function solverFor4x4(grid) {
let number = generateRandom(1, 5, [0, 5]);
if (!number) {
return;
}
console.log(number)
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if(grid[i][j] == 0 && isSafe(grid, number, i, j)) {
grid[i][j] = number;
break;
}
}
}
showSolution(grid);
}
function isSafe(grid, number, i, j) {
if(isSafeRow(grid, number, i, j) && isSafeColumn(grid, number, i, j) && isSafeArea(grid, number, i, j)) {
return true;
}
return false;
}
function isSafeRow(grid, number, i, j) {
return !grid[i].includes(number);
}
function isSafeColumn(grid, number, i, j) {
for (let i = 0; i < grid.length; i++) {
if(grid[i][j] == number) {
return false;
}
}
return true;
}
function isSafeArea(grid, number, i, j) {
return true;
}
function generateRandom(min, max, exclude) {
let random;
let counter = 0;
const maxIterations = 100;
while (!random && counter < maxIterations) {
const x = Math.floor(Math.random() * (max - min + 1)) + min;
if (exclude.indexOf(x) === -1) {
random = x;
}
counter++;
}
return random || null;
}

It looks like the issue with the code is that it does not update the grid with the number placed if all checks return true. Also, the "isSafe" function does not return false if one of the checks fail. Try modifying the code as follows:
function solverFor4x4(grid) {
let number = generateRandom(1, 5, [0, 5]);
if (!number) {
return;
}
console.log(number)
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
if(grid[i][j] == 0 && isSafe(grid, number, i, j)) {
grid[i][j] = number;
solverFor4x4(grid);
}
}
}
showSolution(grid);
}
function isSafe(grid, number, i, j) {
if(isSafeRow(grid, number, i, j) && isSafeColumn(grid, number, i, j) && isSafeArea(grid, number, i, j)) {
return true;
}
return false;
}
function isSafeRow(grid, number, i, j) {
if (grid[i].includes(number)) {
return false;
} else {
return true;
}
}
function isSafeColumn(grid, number, i, j) {
let array = [];
for (let i = 0; i < grid.length; i++) {
if(grid[i][j] == number) {
return false;
} else {
array.push(grid[i][j]);
}
}
if(array.includes(number)) {
return false;
} else {
return true;
}
}
This should solve the problem, but keep in mind that the function may still not work correctly due to the random number generation approach.

Related

finding a triplet in an array that sums up to a given value in javascript

I am trying to solve this problem in JavaScript:
Given an array and a value in JavaScript, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false.
Now, I wrote some code, and for some reason, it's not working properly.
Here is the code:
A = [1, 4, 45, 6, 10, 8];
sum = 15;
x = A.length;
function find3Numbers(A, x, sum) {
for (i=0; i<(x-2); i++) {
for (j=i+1; j<(x-1); j++) {
for (k=j+1; x; k++) {
if (A[i] + A[j] + A[k] == sum) {
console.log(A[i]);
console.log(A[j]);
console.log(A[k]);
return true
}
return false
}
}
}
}
console.log(find3Numbers(A, x, sum));
Now when I run the code, I get a "false" message.
Any idea, why is that?
You immediately return false if the first triplet you try does not match, when you should only do so after all loops have finished.
A = [1, 4, 45, 6, 10, 8];
sum = 15;
x = A.length;
function find3Numbers(A, x, sum) {
for (i = 0; i < (x - 2); i++) {
for (j = i + 1; j < (x - 1); j++) {
for (k = j + 1; x; k++) {
if (A[i] + A[j] + A[k] == sum) {
console.log(A[i]);
console.log(A[j]);
console.log(A[k]);
return true
}
}
}
}
return false;
}
console.log(find3Numbers(A, x, sum));
Consider sorting the array beforehand for O(n^2) time complexity rather than O(n^3).
Note: O(nlog(n) + n^2) is asymptotically the same as O(n^2).
const find3Numbers = (nums, nums_length, target) => {
nums.sort((a, b) => a - b);
let i = 0;
while (i < nums_length - 2) {
let j = i + 1;
let k = nums_length - 1;
while (j < k) {
curr_sum = nums[i] + nums[j] + nums[k];
if (curr_sum < target) {
j++;
while (j < k && nums[j] == nums[j - 1]) {
j++;
}
} else if (curr_sum > target) {
k--;
while (j < k && nums[k] == nums[k + 1]) {
k--;
}
} else {
return [nums[i], nums[j], nums[k]];
}
}
i++;
while (i < nums_length - 2 && nums[i] == nums[i - 1]) {
i++;
}
}
return [-1, -1, -1];
}
const A = [1, 4, 45, 6, 10, 8];
const x = A.length;
const sum = 15;
console.log(find3Numbers(A, x, sum));

slice method returns a reference

I'm coding a sudoku solver by backtrack algorithm.
Why does the slice() method in my code return a reference? I know that slice method will return a reference if the array is not Number, String or Boolean. But in my code, the array is filled with 0, how it's possible?
backtrack() {
if (this.state.IsEnd === true)
return true;
const board = this.state.squares.slice(); //board array is the reference of this.state.squares array;
let row, col;
if (!this.findvalid()) {
this.setState({
IsEnd: true
});
return true;
}
let ok = false;
for (let i = 0; i < 9; i++) {
if (ok)
break;
for (let j = 0; j < 9; j++) {
if (board[i][j] === 0 || isNaN(board[i][j])) {
row = i;
col = j;
ok = true;
break;
}
}
}
for (let num = 1; num <= 9; num++) {
if (this.isSafe(row, col, num)) {
board[row][col] = num; /*when board changes,the state squares also changes.*/
this.setState({
squares: board
}); /*when I delete this line,every thing is still the same.*/
if (this.backtrack()) {
return true;
}
board[row][col] = 0;
this.setState({
squares: board
});
}
}
return false;
}
this is my full code
//this function create a board
function createBoard() {
let board = Array(9);
for (let i = 0; i < 9; i++) {
let subarray = Array(9).fill(0);
board[i] = subarray;
}
return board;
}
class App_sudoku_solver extends React.Component {
constructor(props) {
super(props);
this.state = {
squares: createBoard(),
IsEnd: false
}
this.handleChange = this.handleChange.bind(this);
this.SafeBox = this.SafeBox.bind(this);
this.SafeCol = this.SafeCol.bind(this);
this.SafeRow = this.SafeRow.bind(this);
this.isSafe = this.isSafe.bind(this);
this.findvalid = this.findvalid.bind(this);
this.backtrack = this.backtrack.bind(this);
this.solve = this.solve.bind(this);
this.check = this.check.bind(this);
this.restart = this.restart.bind(this);
}
//check if any cell is empty
findvalid() {
const board = this.state.squares.slice();
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
if (board[i][j] === 0 || isNaN(board[i][j]))
return true;
}
}
return false;
}
// check valid 3x3 squares
SafeBox(startrow, startcol, num) {
const board = this.state.squares.slice();
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[startrow + i][startcol + j] === num)
return false;
}
}
return true;
}
//check valid row
SafeRow(row, num) {
const board = this.state.squares.slice();
for (let i = 0; i < 9; i++) {
if (board[row][i] === num)
return false;
}
return true;
}
//check valid column
SafeCol(col, num) {
const board = this.state.squares.slice();
for (let i = 0; i < 9; i++) {
if (board[i][col] === num)
return false;
}
return true;
}
//check if this number is valid in the cell
isSafe(row, col, num) {
return (this.SafeRow(row, num) === true && this.SafeCol(col, num) === true && this.SafeBox(row - row % 3, col - col % 3, num) === true);
}
//solve sudoku by backtrack
backtrack() {
if (this.state.IsEnd === true)
return true;
const board = this.state.squares.slice();
let row, col;
if (!this.findvalid()) {
this.setState({
IsEnd: true
});
return true;
}
let ok = false;
for (let i = 0; i < 9; i++) {
if (ok)
break;
for (let j = 0; j < 9; j++) {
if (board[i][j] === 0 || isNaN(board[i][j])) {
row = i;
col = j;
ok = true;
break;
}
}
}
for (let num = 1; num <= 9; num++) {
if (this.isSafe(row, col, num)) {
board[row][col] = num;
this.setState({
squares: board
});
if (this.backtrack()) {
return true;
}
board[row][col] = 0;
this.setState({
squares: board
});
}
}
return false;
}
this.state.squares is an array of arrays, it is not filled with 0
If the array you are running slice on contains any objects, the method will only copy a reference to them. Since your array contains arrays - and thus, objects, all it's elements are copied only by reference.
function createBoard() {
let board = new Array(9);
for (let i = 0; i < 9; i++) {
let subarray = Array(9).fill(0);
board[i] = subarray;
}
return board;
}
// 2d array containing 9 arrays
let board = createBoard();
console.log("Board: ", board);
const modifiedSlicedBoard = board.slice()[0][2] = 9999999; // I'm modifying the contents of one of the sub-arrays. Because the arrays are copied shallowly, this will also modify the original board
console.log(board, modifiedSlicedBoard);

Return array with factorial number from another array

This function will receive an array of positive integers and it should return a new array with the factorial of each number.
So far I came up with this but it doesn't work and I don't know where is the problem, any ideas?
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
if(nums[i] <= 1) {
return 1;
} else {
arr.push(nums[i] * getFactorials(nums[i] - 1));
}
}
return arr;
}
try this use map
var a = [1, 2, 3, 4, 5];
function fact(x) {
return (x == 0) ? 1 : x * fact(x-1);
}
console.log(a.map(fact));
Try the following:
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
let j, fact;
fact=1;
for(let j=1; j<=nums[i]; j++)
{
fact= fact*j;
}
arr.push(fact);
}
return arr;
}
let res = getFactorials([5,9])
console.log(res);
Try this way:
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
arr.push(factorial(nums[i]));
}
return arr;
}
getFactorials([6,5,3])
const factorial = (n) => {
let res = [];
while(n != 0){
//get all integers less than or equal to n
res.push(n);
n--;
}
return res.reduce((x, y) => {
return x * y;
//reduce the array of integers into a single number via multiplication
});
}
const nums = [1, 2, 3, 4, 5];
const factorialArr = (arr) => {
return arr.map(n => {
//iterate through a list of numbers and return the factorial of each
return factorial(n);
});
}
const result = factorialArr(nums);
console.log(result) -> // Array [ 1, 2, 6, 24, 120 ]
function getFactorials(nums) {
const factNums = nums.map(
function factorial (num) {
return (num == 0 ? 1 : num * factorial(num -1));
}
)
return factNums;
}
#include <stdio.h>
int iFactorial(int iCount)
{
int iProduct = 1;
int iNumber = 1;
while (iNumber <= iCount)
{
iProduct *= iNumber;
iNumber++;
}
return iProduct;
}
int main(void)
{
int iFac[10] = {0};
int iCount = 0;
for (iCount = 0; iCount < 9; iCount++)
iFac[iCount] = iFactorial(iCount);
for (iCount = 0; iCount < 9; iCount++)
printf("\nThe value of the factorial is %d\n", iFac[iCount]);
return 0;
}

Javascript getting the nth prime number

This should return the nth prime (n being the number given by the user). It works fine for the first few numbers (1 returns 2, 2 returns 3, 3 returns 5) but when 5 is given, it returns 9 which isn't prime (it should be 11). This happens with other numbers as well above this (7 returns 15 when it should be 17).
The 'document' stuff is to do with HTML where I'm getting the userValue and to display the prime number.
function isPrime(value) {
for(var i = 2; i < value; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
}
function generatePrime() {
var userValue = document.getElementById("inputValue").value;
var iter = 1;
var returnValue = 2;
//checks for an integer
if (parseInt(userValue) === parseFloat(userValue)) {
//checks if the user inputted a value above 0
if (userValue > 0) {
//loops to find the correct prime
while (iter < userValue) {
if (isPrime(returnValue)) {
returnValue += 1;
iter += 1;
}
if (!isPrime(returnValue)) {
returnValue += 1;
}
}
}
else {
returnValue = "That is not a number above 0!";
}
}
else {
returnValue = "That is not a number!";
}
document.getElementById("returnValue").innerHTML = returnValue;
}
I need help with making this return the correct number.
Try this one.
function nextPrime(value) {
if (value > 2) {
var i, q;
do {
i = 3;
value += 2;
q = Math.floor(Math.sqrt(value));
while (i <= q && value % i) {
i += 2;
}
} while (i <= q);
return value;
}
return value === 2 ? 3 : 2;
}
function generatePrime() {
var userValue = document.getElementById("inputValue").value;
var value = 0, result = [];
for (var i = 0; i < userValue; i++) {
value = nextPrime(value);
result.push(value);
}
document.getElementById("returnValue").innerHTML = result[userValue-1];
}
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
Input value: <input type="text" name="inputValue" id="inputValue"/>
<button onclick="generatePrime()">Prime number</button>
<div id="returnValue">Test: </div>
</body>
</html>
You can try something like this:
function getNthPrimeNumber(n){
var count = 0;
var num = 2;
while(count++ != n){
num = getNextPrimeNumber(num);
}
return num;
}
function getNextPrimeNumber(n){
for(var i = ++n; i< n*n; i++){
if(isPrime(i)) return i
}
return 0;
}
function isPrime(n){
for(var i = 2; i< n; i++)
if (n%i===0)
return false;
return true;
}
console.log(getNthPrimeNumber(0))
console.log(getNthPrimeNumber(2))
console.log(getNthPrimeNumber(5))
You could reduce the range of iteration for function isPrime() :
function isPrime(value) {
for(var i = 2; i < Math.sqrt(value) + 1; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
}
The following is based on Bhaskara Arani's submission, but I added caching.
Note: I also threw in an addition condition to check for palindrome.
This check can be removed via:
while (i <= root && value % i /* && isPalindrome(value) */)
const main = () => {
for (let i = 15; i >= 0; i--) {
console.log(`Palindrome Prime ${i + 1} = ${generatePrime(i)}`);
}
};
const cachedPrimes = [];
const generatePrime = (index) => {
let value = cachedPrimes[cachedPrimes.length - 1] ?? 0;
for (let i = cachedPrimes.length; i <= index; i++) {
value = nextPrime(value);
cachedPrimes.push(value);
}
return cachedPrimes[index];
};
const nextPrime = (value) => {
if (value > 2) {
let i, root;
do {
i = 3; value += 2; root = ~~Math.sqrt(value);
while (i <= root && value % i && isPalindrome(value)) {
i += 2;
}
} while (i <= root);
return value;
}
return value === 2 ? 3 : 2;
};
const isPalindrome = (n) => n === reverse(n);
const reverse = n => +`${n}`.split('').reverse().join('');
main();
.as-console-wrapper { top: 0; max-height: 100% !important; }

How do I sum all prime numbers?

I am working on an excercise to sum all prime numbers from 2 to the parameter. I have worked this far in the code, but am stuck. I believe by using the splice function, I am actually skipping an element because of a changed indices.
function sumPrimes(num) {
var primearray = [];
var sum = 0;
for(var i =2; i <= num; i++){
primearray.push(i);
}
for(var j = 0; j < primearray.length; j++) {
console.log(primearray[j]);
if ((primearray[j]%2===0) && (primearray[j] >2)) {
primearray.splice(j,1);
} else if ((primearray[j]%3===0) && (primearray[j] > 3)) {
primearray.splice(j,1);
console.log(primearray);
} else if ((primearray[j]%5===0) && (primearray[j] > 5)) {
primearray.splice(j,1);
} else if ((primearray[j]%7===0) && (primearray[j] > 7)) {
primearray.splice(j,1);
}
}
sum = primearray.reduce();
return sum;
}
sumPrimes(30);
I haven't utilized the reduce function yet because I am still working on the if else statements.
I found a pretty good solution to the same problem. afmeva was spot on. This is how it works.
function isPrime(val){
//test if number is prime
for(var i=2; i < val; i++){
if(val % i === 0){
return false;
}
}
return true;
}
In the above code we accept a number to determine whether or not it is prime. We then loop from two all the way up until our number minus one because we know that our number will be divisible by itself and one. If the remainder of our value with the current loop value is zero then we know it is not prime so break out and say so.
This article explains very well
function sumPrimes(num) {
var answer = 0;
//loop through all numbers from 2 to input value
for(var i=2; i <= num; i++){
//sum only prime numbers, skip all others
if(isPrime(i)){
answer += i;
}
}
return answer;
}
sumPrimes(977); // 73156
Here's another good resource
function sumPrimes(num) {
let arr = Array.from({length: num+1}, (v, k) => k).slice(2);
let onlyPrimes = arr.filter( (n) => {
let m = n-1;
while (m > 1 && m >= Math.sqrt(n)) {
if ((n % m) === 0)
return false;
m--;
}
return true;
});
return onlyPrimes.reduce((a,b) => a+b);
}
sumPrimes(977);
I have seen lots of people putting all prime numbers into arrays and in order to check if a number is prime, they check from 2 to the number to see if there's a remainder.
You only need to check odd numbers, and only need to count to half the number because a number can't be divisible by any number greater than it has.
Here's my solution:
function sumPrimes(num){
var sum = num>=2?2:0;
for(var i=3;i<=num;i+=2){
var isPrime=true;
for(var j=3;j<(i/2);j++){
if (i%j==0)
{
isPrime=false;
break;
}
}
sum+=isPrime?i:0;
}
return sum;
}
Note: I started from j=2 because we are only checking odd numbers, so they'd never be divisible by 2.
function sumPrimes(num) {
var sumArr= [];
for(var i=0;i<=num;i++){
if(isPrime(i))
sumArr.push(i);
}
sumArr = sumArr.reduce(function(a,b){
return a+b;
})
return sumArr;
}
function isPrime(num) {
if(num < 2) return false;
for (var i = 2; i < num; i++) {
if(num%i === 0)
return false;
}
return true;
}
sumPrimes(10);
something like this?
function isPrime(_num) {
for(var i = 2; i < _num; i++) {
if(!(_num % i)) {
return false
}
}
return true;
}
function sumPrimes(_num) {
var sum = 0;
for(var i = 2; i <= _num; i++) {
if(isPrime(i)) {
sum += i;
}
}
return sum;
}
sumPrimes(20) // 77
sumPrimes(5) // 10
You could do this as well.
function sumPrimes(num) {
var sum = 0;
for (var i = 0; i <= num; i++) {
if (isPrime(i)) {
sum += i;
}
}
return sum;
}
function isPrime(n) {
if (n < 2) { return false; }
if (n !== Math.round(n)) { return false; }
var result = true;
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
result = false;
}
}
return result;
}
Here's my solution. I hope you find it easy to interpret:
function sumPrimes(num) {
// determine if a number is prime
function isPrime(n) {
if (n === 2) return true;
if (n === 3) return true;
if (n % 2 === 0) return false;
if (n % 3 === 0) return false;
var i = 5;
var w = 2;
while (i * i <= n) {
if (n % i === 0) {
return false;
}
i += w;
w = 6 - w;
}
return true;
}
// subtract 1 for 'not being prime' in my context
var sum = isPrime(num) ? num - 1 : -1;
for (var x = 0; x < num; x++) {
if (isPrime(x) === true) {
sum += x;
}
}
return sum;
}
here is my solution to sum of n prime number
function sumOfNPrimeNumber(num){
var sum = 0;
const isPrime = function(n){
if (isNaN(n) || !isFinite(n) || n%1 || n<2) {
return false;
}
if (n%2==0){
return (n==2);
}
var sqrt = Math.sqrt(n);
for (var i = 3; i < sqrt; i+=2) {
if(n%i == 0){
return false;
}
}
return true;
}
const getNextPrime = function* (){
let nextNumber = 2;
while(true){
if(isPrime(nextNumber)){
yield nextNumber;
}
++nextNumber;
}
}
const nextPrime = getNextPrime();
for (var i = 0; i < num; i++) {
sum = sum + nextPrime.next().value;
}
return sum;
}
console.log(sumOfNPrimeNumber(3));
All the above answers make use of helper functions or aren't time efficients.
This is a quick, recursive solution in O(n) time:
// # signature int -> int
// # interpr: returns sum of all prime integers <= num
// assume: num is positive integer
function sumPrimes(num) {
if (num <= 2) {
return 2;
}
let i = 2;
while (i < num) {
if (num % i === 0) {
return sumPrimes(num - 1)
}
i++;
}
return num + sumPrimes(num - 1)
}
// test
sumPrimes(10); // -> 17
function prime_sum(num){
let count=0; *//tracks the no of times number is divided perfectly*
for(let i=1;i<=num;i++){ *//from 1 upto the number*
if(num%i==0){count++};
}
if(count===2){return "Prime"};
return{"Not prime"};
}
console.log(prime_sum(10));//expected output is 17**
//the code receives a number,checks through the range and returns prime if it meets the condition
The following solution uses the Eratosthenes Sieve to sum all prime numbers lower than or equal to num. The first for loop fills an array with size equal to num with true. The second for loop sets to false all non-prime numbers in the array. Then, the last for loop simply iterates through the array to sum all the array indexes i for which the value in the array, i.e., array[i], is equal to true.
/**
* Sum all primes lower or equal than n.
* Uses the Eratosthenes Sieve to find all primes under n.
*/
function sumPrimes(num) {
let array = [];
let output = 0;
// Fill an array of boolean with 'true' from 2 to n.
for (let i = 0; i <= num; i++) {
array.push(true);
}
// Set all multiples of primes to 'false' in the array.
for (let i = 2; i <= Math.sqrt(num); i++) {
if (array[i]) {
for (let j = i * i; j <= num; j += i) {
array[j] = false;
}
}
}
// All array[i] set to 'true' are primes, so we just need to add them all.
for (var i = 2; i <= num; i++) {
if (array[i]) {
output += i;
}
}
return output;
}
console.log(sumPrimes(10)); // 17
console.log(sumPrimes(977)); // 73156
console.log(sumPrimes(250_000_000)); // 197558914577
function sumPrimes(num) {
let output = 0;
// check if num is a prime number
function isPrime(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return false;
}
}
return true;
}
for (let i = 2; i <= num; i++) {
if (isPrime(i)) {
output += i;
}
}
return output;
}
console.log(sumPrimes(10)); // 17
This is what I've done to get primes. I don't know if it's the most efficient, but it works. This is in Java, but can be easily converted to JavaScript. Hopefully this will help point you in the right direction.
final int TOTAL = 10;
int primes[] = new int[TOTAL];
int arrPos = 2;
boolean prime = false;
primes[0] = 2;
for (int i = 2; i < TOTAL; i++) {
prime = false;
int sqrt = (int) Math.sqrt(i);
for (int j = 1; j < arrPos && primes[j] < sqrt; j++) {
if (i % primes[j] != 0) {
prime = true;
} else {
prime = false;
break;
}
}
if (prime == true) {
primes[arrPos] = i;
arrPos++;
}
}

Categories

Resources