Shortest way to get prime numbers JS - javascript

Is there a way to get prime numbers in one line
I was given a task to get the largest prime number in an array in one line is that even possible?!
Given an array of numbers. Create a function which returns the largest prime number. (​NOTE*​,
it should be written only 1 line of code). ​(2)
let arr1 = [1,5,7,6,9,10,13,11,12]
function largestPrime(arr) {
// write your code here... }
}

Referring the great answer of #Sergio to the question: Number prime test in JavaScript. You can filter the prime numbers in the array then get the largest one by using the Math.max function.
let arr1 = [1,5,7,6,9,10,13,11,12]
function largestPrime(arr) {
return Math.max(...arr.filter((n) => { return ![...Array(n).keys()].slice(2).map(i => !(n%i)).includes(true) && ![0,1].includes(n) }));
}
console.log(largestPrime(arr1));

Related

How to get sums of subarrays

While solving online code exercises, I came across this one:
Given a 1-dimensional array of numbers and the number of queries, where each query has start index a, end index b and a number c, find the sum of numbers between indexes a and b (inclusive). For each occurrence of zero within the range [a,b], add the value of c to the sum. For example, numbers = [4,6,0,10], queries = [1,3,20] => for this example we need to get the sum of [4,6,0] (indexes 1-3), and because [4,6,0] has 0, we also need to add 20.
This is my code so far:
function findSum(numbers, queries) {
//declare empty array that will store the numbers
let arr = []
// declare initial sum
let sum = 0;
// get the last element of queries (c)
let lastElement = queries[0].pop()
// loop through queries and push numbers to arr, to sum them in the end
queries[0].slice(0, 2).forEach(x => {
arr.push(numbers[x - 1])
})
// check if arr has 0
let zero = arr.filter(el => el === 0)
// if arr has 0, according to the instructions we need to add the c of the q
if (zero.length != 0) {
sum = arr.reduce((a, b) => a + b, 0) + lastElement
}
else {
sum = arr.reduce((a, b) => a + b, 0)
}
return sum
}
My code works if queries is an array, but in some test cases queries may be array of arrays like [ [ 2, 2, 20 ], [ 1, 2, 10 ] ]. I don't know know how to check the numbers in case if queries is array of arrays. Any suggestions are greatly appreciated.
in some test cases queries may be array of arrays
I would expect that this would always be the case, not just in some cases. This is also clear from your code:
queries[0].pop()
This assumes a 2-dimensional array! The problem is not that you sometimes get a 1-dimensional array and other times a 2-dimensional array. The problem is that although you always get a 2-dimensional array, your code is only looking at the first query -- the one that sits at queries[0].
Instead, you should loop over all queries.
I also assume that the return value of your function must be an array, having an answer for each of the queries. This means that you probably want to have code like this:
function findSum(numbers, queries) {
return queries.map(query => {
// solve the single query
return sum;
});
}
Note that your code is not making the sum correctly, as your arr will have a length of 2 (arr.push(numbers[x - 1]) is executed exactly twice), yet the query could indicate a range with 100 values and you should derive the sum of those 100 values, not just of two.
But even if you fix all that, you'll end up with an inefficient solution that will have to iterate over many values in the input array multiple times. This needs a smarter approach.
Try to think of a way to analyse the input before processing any queries yet. Would there be something useful you could build that would help to quickly get a sum of a subarray without having to iterate that subsection again?
Here are some hints:
Hint #1
Use the following truth:
sum(numbers.slice(start, end)) == sum(numbers.slice(0, end)) - sum(numbers.slice(0, start - 1))
Hint #2
What if you would know the sum from the start of the array to any given index? Like a running sum... So for numbers=[4, 8, 0, 3] you would know [4, 12, 12, 15]. Would that help in calculating a sum for a certain range of [start, end]?
Hint #3
How could you apply the same principle for the special treatment of zeroes?

Can anyone explain recursive in Nth fibonacci?

I was doing a coding algorithm to find the nth number which is the sum of the (n-1)th and (n-2)th numbers.
Here was the solution
function getNthFib(n, hashTable = {1: 0, 2: 1}) {
if (n in hashTable) {
return hashTable[n]
} else {
hashTable[n] = getNthFib(n - 1, hashTable) + getNthFib(n - 2, hashTable)
return hashTable[n]
}
}
can anyone explain to me in the else block of what is actually happening? i am confused with this recursive concept
Recursive Fibonacci works beacse the next number is the last two numbers combined. Eg 3 + 5 = 8 and then 5 + 8 = 13. The recursive solution finds the value of the 2 numbers to add to the next, and then finds the numbers before, etc. The hashtable, which is a plain object, maps precomputed values so it does not have to compute them again, as recursive Fibonacci has a O(n!) time complexity without a table or cache.

How would you find the values in an array that equal the sum a specified number?

I'm working on creating a basic function that takes in 2 parameters -- array and num.
In the array are a list of numbers and the output could essentially generate 3 results:
0 with no two numbers that equal the sum equal to num.
1 variation of two numbers that is equal to the sum that is num
Multiple variations of 2 numbers that equal the sum that is num
I've been working with filter and reduce but haven't been able to produce the desired output.
Let's say I have a nums array of [3,6,9,18] and have a specified num value of 15.
var findNumSum = function(nums, num) {
function val(a, b) {
a + b === num;
var es = [a, b]
return es;
}
var result1 = nums.filter(val); // [3,6,9,18]
var result2 = nums.reduce(val); // [[6, 9], 18]] -- I've been able to isolate the num values but wasn't the result I was expecting. I'm still pretty fresh at this.
};
Let's assume you want to find sums for the number 6. Check the first number of the array, let it be 2. You now want to know if there's a 4 in you array, so you check that. Do this process for all the numbers in the array and remove duplicates.
Maybe this could help ?
Here is a little snippets along the lines of the previous suggestions:
const arr=[...Array(25)].map((_,v,)=>v), // create an array with 25 numbers
findsum=(ar,sum)=>
ar.reduce((a,c,i)=>
(c>sum || ar.slice(i+1).forEach(v=>
c+v-sum || a.push([c,v])),a)
,[] );
console.log(findsum(arr,27)) // find all possible pairs that add up to 27
Maybe it is helpful to you?
Only if the first condition c>sum is false the following ar.slice(i+1).forEach(...) will be executed. inside the forEach()-callback function the a.push([c,v]) will only be performed c+v-sum is "falsy" i. e. ==0.

Determine if product of integers is even or odd in javascript

I am trying to determine if the product of all the integers is even or odd.
I have a list of integers, and I want to check if the product of the integers is even or odd.
For example:
determineIfEvenOrOdd([6,7,9,9])
function determineIfEvenOrOdd(int_array) {
//Code here
}
I was thinking of looping through the array and multiplying the numbers to find out the product of the array integers. But then I thought it would be expensive to do this if the array was huge.
I am a beginner, and would like to know a possible approach for the solution.
If your list of numbers contains an even number, the product of all numbers will be even.
You can loop through the list of numbers and check each individual number for even-ness with a conditional statement like:
// Put this code inside function determineIfEvenOrOdd
var even = false;
for (let i=0; i<int_array.length; i++) {
if (i%2==0) {
even = true;
break;
}
}
An efficient way would be to check whether there is any number that is even, if so, the product is even. If there aren't any numbers that are even, then the product is odd.
function isProductEven(arr)
{
for (let i = 0; i < arr.length; i++)
if ((arr[i] & 1) === 0) return true;
return false;
}
console.log(isProductEven([6, 7, 9, 9]))
This outputs true as the product of these numbers is even.
The most concise solution would be this:
const isProductEven = arr =>
arr.some(e=>!(e%2));
This checks if at least one of the numbers in the array is even by testing if its remainder from division by 2 equals to 0. You can use it directly as well:
console.log([1,2,3].some(e=>!(e%2))); // true
console.log([1,3,5].some(e=>!(e%2))); // false
console.log([].some(e=>!(e%2))); // false
I usually implement Array.reduce to achieve this. It's easy to implement.
function isArrayProductEven(arr) {
return !(arr.reduce((a, b) => a * b, 1) % 2);
}
console.log(isArrayProductEven([1,2,3,4,5]));
console.log(isArrayProductEven([1,3,5,7,9]));
How this works is: multiply all numbers in the array and check the remainder of 2 (odd / even) to determine if the result is odd (false) or even (true).

Javascript - sorting arrays containing positive and negative "decimal" numbers

I originally had the following callback passed as a parameter to the javascript array sort() function:
function sortNumber(a,b) {
return a-b;
}
However this doesn't work when my array contains positive and negative decimal numbers (i.e. -107.578, 97.453 etc.) How would I modify this to sort properly?
I don't see any problems with that function. Here's my test code:
var nums = [10, 5, 40, 25, -3412,4212, -107.578, 97.453];
function sortNumber(a,b){
return a - b;
}
alert( nums.sort(sortNumber) );
Can you show some more of your code? It might be a problem with the array.

Categories

Resources