Javascript - simple exercises - javascript

I have a task to write a function getEvenAverage, which should take only one argument - array. This function should return an average value of even numbers from this array. If in the array there aren't any even numbers the function should return null.
I'd really appreciate any feedback :-)
function getEvenAverage(tab) {
{
if (i % 2 === 0) {
for (var i = 0; i < tab.length; i++) {
sum += parseInt(tab[i], 10);
}
var avg = sum / tab.length;
} else
console.log('null');
}
}

You say you need to return something, so return it. Also move your if statement inside your for loop, and fix a few other syntax errors. And as pointed out in the comments, you should divide sum by the number of even numbers to get your avg:
function getEvenAverage(tab) {
var sum = 0;
var evens = 0;
for (var i = 0; i < tab.length; i++) {
if (i % 2 === 0) {
sum += parseInt(tab[i], 10);
evens++;
}
}
if (evens == 0) {
console.log("null");
return null;
} else {
var avg = sum / evens;
return avg;
}
}
console.log(getEvenAverage([1, 2, 3]));

You could also do it with the array reduce, with a single array traversal
const reducer = (acc, val) => {
let {
sum,
count
} = acc;
return (val % 2 === 0 ? {
sum: sum + val,
count: count + 1
} : acc);
};
const getEvenAverage = (input) => {
const initialValue = {
sum: 0,
count: 0
};
const output = input.reduce(reducer, initialValue);
if (output.count === 0) {
return null;
} else {
return output.sum / output.count;
}
};
console.log(getEvenAverage([1, 2, 3]));

Here is the correct function.
function getEvenAverage(tab) {
var sum = 0, count = 0;
for (var i = 0; i < tab.length; i++) {
if (i % 2 === 0) {
sum += parseInt(tab[i], 10);
count++;
}
}
if(sum > 0)
return (sum / count);
return null;
}
Wish You happy coding.

Other than using a for loop, you can utilize filter and reduce Array methods.
function getEvenAverage(arr) {
const newArr = arr.filter(number => number % 2 === 0);
return newArr.length > 0 ? newArr.reduce((acc, num) => acc + num) / newArr.length : null;
}
console.log(getEvenAverage([1, 2, 3, 4]));
console.log(getEvenAverage([1, 3, 5, 7]));

Try this function,
function getEvenAverage(tab) {
var numberOfEvens = 0;
var sum = 0;
for(var i=0;i<tab.length;i++){
if(tab[i]%2 == 0 ){
numberOfEvens++;
sum += tab[i];
}
}
if(numberOfEvens == 0)return null;
return sum/numberOfEvens;
}
console.log(getEvenAverage([0,1,2,3,4,5]))
console.log(getEvenAverage([1,2,3,4,5]))
console.log(getEvenAverage([0,1,11,3,4,5]))
console.log(getEvenAverage([1,5,3]))

You need only the even numbers, so first filter the array into a new array, then sum all the numbers (using reduce or a for loop) and divide by its length.
function getEvenAverage(array) {
if (!Array.isArray(array)) return null; // not a must if you're sure you pass an array
var evenArray = array.filter(function(value) {
return value % 2 === 0
});
if (evenArray.length === 0) return null;
var evenSum = evenArray.reduce(function(total, current) {
return total + current;
});
var evenAvg = evenSum / evenArray.length;
return evenAvg;
}
console.log(getEvenAverage("not an array"));
console.log(getEvenAverage([1,3,7])); // no even numbers
console.log(getEvenAverage([1,2,3])); // single even number
console.log(getEvenAverage([2,2,2])); // only even numbers
console.log(getEvenAverage([1,2,3,10,18])); // bigger array
console.log(getEvenAverage([0,1])); // 0 is also even

function getEvenAverage(arr){
var evenNumbers = []; // we use an array to hold all of our evenNumbers
for (var el of arr){ // we loop over the received array to check the received
if(el % 2 !=0){ // if the number is even
evenNumbers.push(el); // we add it to our evenNumbers array
}
}
if(evenNumbers.length == 0){ // when we have no even Number
return false; // we then return false
}
else{
// the next block of code calculates the average of the even values
return evenNumbers.reduce((pv,cv) => pv+cv,0)/evenNumbers.length;
}
}
var evenNumbers = [4,2,3,6,5,9];
getEvenAverage(evenNumbers); // returns 5.666666666666667
getEvenAverage([2,4,6,8]); // returns false

Related

How to make a function that returns the factorial of each integer in an array

I'm new to coding and have been given this question that I cannot seem to get right:
Create a function that takes an array of positive integers and returns an array of the factorials of these numbers.
E.g. [4, 3, 2] => [24, 6, 2]
The factorial of a number is the product of that number and all the integers below it.
E.g. the factorial of 4 is 4 * 3 * 2 * 1 = 24
If the number is less than 0, reject it.
The code that I have created is this;
function getFactorials(nums) {
if (nums === 0 || nums === 1)
return 1;
for (var i = nums - 1; i >= 1; i--) {
nums *= i;
}
return nums;
}
The code is being run against this test;
describe("getFactorials", () => {
it("returns [] when passed []", () => {
expect(getFactorials([])).to.eql([]);
});
it("returns one factorial", () => {
expect(getFactorials([3])).to.eql([6]);
});
it("returns multiple factorials", () => {
expect(getFactorials([3, 4, 5])).to.eql([6, 24, 120]);
});
it("returns largest factorials", () => {
expect(getFactorials([3, 8, 9, 10])).to.eql([6, 40320, 362880, 3628800]);
});
});
How should I do this?
First off, make a recursive function that calculates the factorial of a single number:
function factorial(num) {
if (num == 0 || num == 1) {
return 1;
}
return num * factorial(num - 1);
}
Then to do it for an array, just use Array.prototype.map() like so:
function getFactorials(arr) {
var result = arr.map(x => factorial(x));
return result;
}
Here's a demonstration:
function factorial(num) {
if (num == 0 || num == 1) {
return 1;
}
return num * factorial(num - 1);
}
function getFactorials(arr) {
var result = arr.map(x => factorial(x));
return result;
}
console.log(getFactorials([4, 8, 10]));
console.log(getFactorials([]));
console.log(getFactorials([1, 2, 3, 4, 5]));
Hopefully this helps!
You need to separate function into two functions, one for iterating the array and collecting the calculated values and the other to get the facorial of a number.
function getFactorials(nums) {
var result = [],
i;
for (i = 0; i < nums.length; i++) {
result.push(getFactorial(nums[i]));
}
return result;
}
function getFactorial(n) {
if (n === 0 || n === 1) return 1;
return n * getFactorial(n - 1);
}
console.log(getFactorials([]));
console.log(getFactorials([3]));
console.log(getFactorials([3, 4, 5]));
console.log(getFactorials([3, 8, 9, 10]));
This method will take an array of numbers and will return an array of factorial numbers of them,
function getFactorials(array) {
var facArray = [];
for (var j = 0; j < array.length; j++) {
num = array[j];
if (num === 0 || num === 1)
return 1;
for (var i = num - 1; i >= 1; i--) {
num *= i;
}
facArray.push(num);
}
return facArray;
}
console.log(getFactorials([4, 3, 2]));
function getFactorials(nums) {
return numbers = Array.from(nums).map(function factorializeSingleNumber(num) {
if (num == 0 || num == 1) return 1
else return num * factorializeSingleNumber(num - 1)
})
}
The best way I find of tackling these is to break the problem down. So in this case, work a solution that factorializes a single number. When that is working you can add this 'working code' into a map or loop, to work through the array.
My above solution uses recursion but could be a simple 'for loop' too

Javascript reduce not working after function?

Not too sure where I've gone wrong here, expecting to factorialize 5 (1*2*3*4*5 = 120) by turning 5 into a string of [1,2,3,4,5] and then using reduce to multiply the string all together. When I run the code, it just gives me [1,2,3,4,5]...
var arr = [];
function factorialize(num) {
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
var factors = 0;
factors = arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
}, 0); // Expecting 120, instead result = [1,2,3,4,5]
factorialize(5);
Forgive the long route - my first week of Javascript!
arr is empty, you should give it the resulting array of the factorisation first, and you should multiply, not add, and when multiplying, the starting value is 1 not 0:
var arr = [];
function factorialize(num) {
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
arr = factorialize(5); // give it the value
var factors = arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal; // multiply, don't add
}, 1); // start with 1 when multiplying
console.log(arr);
console.log(factors);
If you just want to calculate the factorial:
function factorial(num) {
var res = 1;
for (var i = 2; i <= num; i++) {
res *= i;
}
return res;
}
console.log('factorial(5) = ' + factorial(5));
console.log('factorial(10) = ' + factorial(10));
You are not calling factors. factorialize(5); by doing this you are just calling function factorialize(num) which will give you array(of 1...num).
(Additional info)And also in reduce you are adding + instard of multiplying * so change that too and
factors = arr.reduce(function(previousVal, currentVal) {
return previousVal + currentVal;
}, 0);
^
|_ either initialize it to 1 or remove this.
See below code. I just create array and then apply reduce on that array.
function factorialize(num) {
var arr = [];
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
});
}
console.log(factorialize(5));
var arr = [];
function factorialize(num) {
for (var i = 1; i <= num; i++) {
arr.push(i);
}
var factors = 0;
factors = arr.reduce(function (previousVal, currentVal) {
return previousVal * currentVal;
});
return factors
}
factorialize(5); // 120
You could get first the factors and then multiply in Array#reduce the factors.
I suggest to name the function what it does and move the array declaration inside of the function, because the function returns this array.
For getting the product, you need to multiply the values and use 1 as neutral start value for getting a product out of the numbers.
function getFactors(num) {
var i, arr = [];
for (i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
var factors = getFactors(5),
product = factors.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
}, 1);
console.log(factors);
console.log(product);
Put the global variable arr inside of the function factorialize.
Get the returned array and then execute the function reduce.
You need to multiply rather than to add the numbers.
Start the reduce with initialValue = 1, this is to avoid 0 * n.
function factorialize(num) {
var arr = [];
for (var i = 1; i <= num; i++) {
arr.push(i);
}
return arr;
}
var arr = factorialize(5);
var factors = arr.reduce(function(previousVal, currentVal) {
return previousVal * currentVal;
}, 1);
console.log(factors)
Issue is with the initial value set to 0 and instead of multiplying numbers, it is being added
arr.reduce(callback, initValue)
arr = [1,2,3,4,5]
In the code provided, it accumulates in below format
arr.reduce(function(previousVal, currentVal) {
return previousVal + currentVal;
}, 0);
First call -> 0 + 1 = 1 (factors = 1)
Second call -> 0 + 2 = 2 (factors = 2)
First call -> 0 + 3 = 3 (factors = 3)
First call -> 0 + 4 = 4 (factors = 10)
First call -> 0 + 5 = 5 (factors = 15)
To achieve expected result, use below option
var arr = []; // initialize array arr
function factorialize(num) {
//for loop to push 1,2 ,3, 4, 5 to arr array
for (var i = 1; i <= num; i++) {
arr.push(i);
}
// return arr.reduce value by multiplying all values in array, default initial value is first element
return arr.reduce(function(previousVal, currentVal) {
//console log to debug and display loop values
console.log(previousVal, currentVal);
return previousVal * currentVal;
});
}
console.log("output", factorialize(5));
code sample - https://codepen.io/nagasai/pen/YaQKZw?editors=1010

Pair of elements from a specified array whose sum equals a specific target number

I am in mid of my JavaScript session. Find this code in my coding exercise. I understand the logic but I didn't get this map[nums[x]] condition.
function twoSum(nums, target_num) {
var map = [];
var indexnum = [];
for (var x = 0; x < nums.length; x++)
{
if (map[nums[x]] != null)
// what they meant by map[nums[x]]
{
index = map[nums[x]];
indexnum[0] = index+1;
indexnum[1] = x+1;
break;
}
else
{
map[target_num - nums[x]] = x;
}
}
return indexnum;
}
console.log(twoSum([10,20,10,40,50,60,70],50));
I am trying to get the Pair of elements from a specified array whose sum equals a specific target number. I have written below code.
function arraypair(array,sum){
for (i = 0;i < array.length;i++) {
var first = array[i];
for (j = i + 1;j < array.length;j++) {
var second = array[j];
if ((first + second) == sum) {
alert('First: ' + first + ' Second ' + second + ' SUM ' + sum);
console.log('First: ' + first + ' Second ' + second);
}
}
}
}
var a = [2, 4, 3, 5, 6, -2, 4, 7, 8, 9];
arraypair(a,7);
Is there any optimized way than above two solutions? Can some one explain the first solution what exactly map[nums[x]] this condition points to?
Using HashMap approach using time complexity approx O(n),below is the following code:
let twoSum = (array, sum) => {
let hashMap = {},
results = []
for (let i = 0; i < array.length; i++){
if (hashMap[array[i]]){
results.push([hashMap[array[i]], array[i]])
}else{
hashMap[sum - array[i]] = array[i];
}
}
return results;
}
console.log(twoSum([10,20,10,40,50,60,70,30],50));
result:
{[10, 40],[20, 30]}
I think the code is self explanatory ,even if you want help to understand it,let me know.I will be happy enough to for its explanation.
Hope it helps..
that map value you're seeing is a lookup table and that twoSum method has implemented what's called Dynamic Programming
In Dynamic Programming, you store values of your computations which you can re-use later on to find the solution.
Lets investigate how it works to better understand it:
twoSum([10,20,40,50,60,70], 50)
//I removed one of the duplicate 10s to make the example simpler
In iteration 0:
value is 10. Our target number is 50. When I see the number 10 in index 0, I make a note that if I ever find a 40 (50 - 10 = 40) in this list, then I can find its pair in index 0.
So in our map, 40 points to 0.
In iteration 2:
value is 40. I look at map my map to see I previously found a pair for 40.
map[nums[x]] (which is the same as map[40]) will return 0.
That means I have a pair for 40 at index 0.
0 and 2 make a pair.
Does that make any sense now?
Unlike in your solution where you have 2 nested loops, you can store previously computed values. This will save you processing time, but waste more space in the memory (because the lookup table will be needing the memory)
Also since you're writing this in javascript, your map can be an object instead of an array. It'll also make debugging a lot easier ;)
function twoSum(arr, S) {
const sum = [];
for(let i = 0; i< arr.length; i++) {
for(let j = i+1; j < arr.length; j++) {
if(S == arr[i] + arr[j]) sum.push([arr[i],arr[j]])
}
}
return sum
}
Brute Force not best way to solve but it works.
Please try the below code. It will give you all the unique pairs whose sum will be equal to the targetSum. It performs the binary search so will be better in performance. The time complexity of this solution is O(NLogN)
((arr,targetSum) => {
if ((arr && arr.length === 0) || targetSum === undefined) {
return false;
} else {
for (let x = 0; x <=arr.length -1; x++) {
let partnerInPair = targetSum - arr[x];
let start = x+1;
let end = (arr.length) - 2;
while(start <= end) {
let mid = parseInt(((start + end)/2));
if (arr[mid] === partnerInPair) {
console.log(`Pairs are ${arr[x]} and ${arr[mid]} `);
break;
} else if(partnerInPair < arr[mid]) {
end = mid - 1;
} else if(partnerInPair > arr[mid]) {
start = mid + 1;
}
}
};
};
})([0,1,2,3,4,5,6,7,8,9], 10)
function twoSum(arr, target) {
let res = [];
let indexes = [];
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (target === arr[i] + arr[j] && !indexes.includes(i) && !indexes.includes(j)) {
res.push([arr[i], arr[j]]);
indexes.push(i);
indexes.push(j);
}
}
}
return res;
}
console.log('Result - ',
twoSum([1,2,3,4,5,6,6,6,6,6,6,6,6,6,7,8,9,10], 12)
);
Brute force.
const findTwoNum = ((arr, value) => {
let result = [];
for(let i= 0; i< arr.length-1; i++) {
if(arr[i] > value) {
continue;
}
if(arr.includes(value-arr[i])) {
result.push(arr[i]);
result.push(value-arr[i]);
break;;
}
}
return result;
});
let arr = [20,10,40,50,60,70,30];
const value = 120;
console.log(findTwoNum(arr, value));
OUTPUT : Array [50, 70]
function twoSum(arr){
let constant = 17;
for(let i=0;i<arr.length-2;i++){
for(let j=i+1;j<arr.length;j++){
if(arr[i]+arr[j] === constant){
console.log(arr[i],arr[j]);
}
}
}
}
let myArr = [2, 4, 3, 5, 7, 8, 9];
function getPair(arr, targetNum) {
for (let i = 0; i < arr.length; i++) {
let cNum = arr[i]; //my current number
for (let j = i; j < arr.length; j++) {
if (cNum !== arr[j] && cNum + arr[j] === targetNum) {
let pair = {};
pair.key1 = cNum;
pair.key2 = arr[j];
console.log(pair);
}
}
}
}
getPair(myArr, 7)
let sumArray = (arr,target) => {
let ar = []
arr.forEach((element,index) => {
console.log(index);
arr.forEach((element2, index2) => {
if( (index2 > index) && (element + element2 == target)){
ar.push({element, element2})
}
});
});
return ar
}
console.log(sumArray([8, 7, 2, 5, 3, 1],10))
Use {} hash object for storing and fast lookups.
Use simple for loop so you can return as soon as you find the right combo; array methods like .forEach() have to finish iterating no matter what.
And make sure you handle edges cases like this: twoSum([1,2,3,4], 8)---that should return undefined, but if you don't check for !== i (see below), you would erroneously return [4,4]. Think about why that is...
function twoSum(nums, target) {
const lookup = {};
for (let i = 0; i < nums.length; i++) {
const n = nums[i];
if (lookup[n] === undefined) {//lookup n; seen it before?
lookup[n] = i; //no, so add to dictionary with index as value
}
//seen target - n before? if so, is it different than n?
if (lookup[target - n] !== undefined && lookup[target - n] !== i) {
return [target - n, n];//yep, so we return our answer!
}
}
return undefined;//didn't find anything, so return undefined
}
We can fix this with simple JS object as well.
const twoSum = (arr, num) => {
let obj = {};
let res = [];
arr.map(item => {
let com = num - item;
if (obj[com]) {
res.push([obj[com], item]);
} else {
obj[item] = item;
}
});
return res;
};
console.log(twoSum([2, 3, 2, 5, 4, 9, 6, 8, 8, 7], 10));
// Output: [ [ 4, 6 ], [ 2, 8 ], [ 2, 8 ], [ 3, 7 ] ]
Solution In Java
Solution 1
public static int[] twoNumberSum(int[] array, int targetSum) {
for(int i=0;i<array.length;i++){
int first=array[i];
for(int j=i+1;j<array.length;j++){
int second=array[j];
if(first+second==targetSum){
return new int[]{first,second};
}
}
}
return new int[0];
}
Solution 2
public static int[] twoNumberSum(int[] array, int targetSum) {
Set<Integer> nums=new HashSet<Integer>();
for(int num:array){
int pmatch=targetSum-num;
if(nums.contains(pmatch)){
return new int[]{pmatch,num};
}else{
nums.add(num);
}
}
return new int[0];
}
Solution 3
public static int[] twoNumberSum(int[] array, int targetSum) {
Arrays.sort(array);
int left=0;
int right=array.length-1;
while(left<right){
int currentSum=array[left]+array[right];
if(currentSum==targetSum){
return new int[]{array[left],array[right]};
}else if(currentSum<targetSum){
left++;
}else if(currentSum>targetSum){
right--;
}
}
return new int[0];
}
function findPairOfNumbers(arr, targetSum) {
var low = 0, high = arr.length - 1, sum, result = [];
while(low < high) {
sum = arr[low] + arr[high];
if(sum < targetSum)
low++;
else if(sum > targetSum)
high--;
else if(sum === targetSum) {
result.push({val1: arr[low], val2: arr[high]});
high--;
}
}
return (result || false);
}
var pairs = findPairOfNumbers([1,2,3,4,4,5], 8);
if(pairs.length) {
console.log(pairs);
} else {
console.log("No pair of numbers found that sums to " + 8);
}
Simple Solution would be in javascript is:
var arr = [7,5,10,-5,9,14,45,77,5,3];
var arrLen = arr.length;
var sum = 15;
function findSumOfArrayInGiven (arr, arrLen, sum){
var left = 0;
var right = arrLen - 1;
// Sort Array in Ascending Order
arr = arr.sort(function(a, b) {
return a - b;
})
// Iterate Over
while(left < right){
if(arr[left] + arr[right] === sum){
return {
res : true,
matchNum: arr[left] + ' + ' + arr[right]
};
}else if(arr[left] + arr[right] < sum){
left++;
}else{
right--;
}
}
return 0;
}
var resp = findSumOfArrayInGiven (arr, arrLen, sum);
// Display Desired output
if(resp.res === true){
console.log('Matching Numbers are: ' + resp.matchNum +' = '+ sum);
}else{
console.log('There are no matching numbers of given sum');
}
Runtime test JSBin: https://jsbin.com/vuhitudebi/edit?js,console
Runtime test JSFiddle: https://jsfiddle.net/arbaazshaikh919/de0amjxt/4/
function sumOfTwo(array, sumNumber) {
for (i of array) {
for (j of array) {
if (i + j === sumNumber) {
console.log([i, j])
}
}
}
}
sumOfTwo([1, 2, 3], 4)
function twoSum(args , total) {
let obj = [];
let a = args.length;
for(let i = 0 ; i < a ; i++){
for(let j = 0; j < a ; j++){
if(args[i] + args[j] == total) {
obj.push([args[i] , args[j]])
}
}
}
console.log(obj)}
twoSum([10,20,10,40,50,60,70,30],60);
/* */

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++;
}
}

JavaScript recursive loop to sum all integers from nested array

arr will be an array, containing integers, strings and/or arrays like itself. Sum all the integers you find, anywhere in the nest of arrays.
This is what I came up with, but still not right yet
function arraySum(arr) {
var sum = 0;
var sum1 = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === Math.round(arr[i])) { //check if its an integar
sum += arr[i];
}
if (arr[i] instanceof Array) {
for (var n = 0; n < arr[i].length; n++) {
sum1 += arr[i][n];
}
}
}
console.log(sum + sum1);
}
var sumArr = [[[[[[[[[1]]]]]]]], 1]; // => 101. SHOULD BE 2
arraySum(sumArr);
function arraySum(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array) { sum += arraySum(arr[i]);}
if (arr[i] === Math.round(arr[i])) {sum += arr[i];}
}
return sum;
}
What about using reduce recursively?
function arrSum(arr) {
return arr.reduce(function fn(a, b) {
if (Array.isArray(b)) {
return b.reduce(fn, a);
} else if (b === Math.round(b)) {
return a + b;
}
return a;
}, 0);
}
The reduce() method applies a function against an accumulator and each
value of the array (from left-to-right) has to reduce it to a single
value.
function add(array){
return(array+"").match(/-?\d+(?:\.\d+)?/g).reduce(function(a,b) {
return +a+ +b;
});
}
That uses regex to parse a stringified array but it should work just fine.
So then there'll be an array with only the numbers. Those get parsed into a .reduce() which adds them. The best I could think of :)
help from: mdn
function add(n){return JSON.stringify(n).match(/[^\D]+/g).reduce(function(n,r){return 1*n+1*r})} is what came out of http://jscompress.com
SPEED: 0.04395800351630896s
Either 11% faster than other answers, or my Math's terrible
A more supported answer:
function add (array) {
var nums = JSON.stringify(array).match(/[\d\-]+/g),
i,
sum = 0;
for (i = 0; i < nums.length; i += 1) {
sum += parseInt(nums[i], 10);
}
return sum;
}
You can solve this using recursive functions, try with something like this:
function arraySum(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === Math.round(arr[i])) {
sum += arr[i];
}
if (arr[i] instanceof Array) {
sum += arraySum(arr[i]); //This will apply the same function to the current Array element which is an Array
}
}
return sum; //To have the sum of the actual Array
}
var sumArr = [[[[[[[[[1]]]]]]]], 1];
console.log(arraySum(sumArr)); //now it returns 2
Try this :
function arraySum(arr) {
return arr.reduce(function(s, n) {
return s + ((n instanceof Array) ? arraySum(n) : +n || 0);
}, 0);
}
+n attempts to convert strings to integers, defaulting to zero if +n yields NaN.
http://jsfiddle.net/3z7pakfx/
Here is a solution that doesn't rely on iteration:
var arraySum = function(array) {
if (array.length === 0) {
return 0;
}
var rest = array.slice();
var next = rest.pop();
if (next instanceof Array) {
return arraySum(next) + arraySum(rest);
} else {
return next + arraySum(rest);
}
};
The sum of any value, v, and more values is -
If we do not have a value, v, return the empty sum, 0
By induction, we have a value, v. If the value is an array, return the sum of v plus the sum of more
By induction, we have a value v that is not an array. Return the numeric value of v plus the sum of more
const sum = ([ v, ...more ]) =>
v === undefined
? 0 // 1
: Array.isArray(v)
? sum(v) + sum(more) // 2
: Number(v) + sum(more) // 3
const result =
sum([[[[[[[[[1]]]]]]]], 1])
console.log(result)
// 2

Categories

Resources