简体   繁体   English

确定 javascript 中整数的乘积是偶数还是奇数

[英]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:这通过测试其除以 2 的余数是否等于 0 来检查数组中的至少一个数字是否为偶数。您也可以直接使用它:

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.我通常实现 Array.reduce 来实现这一点。 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).它的工作原理是:将数组中的所有数字相乘并检查 2 的余数(奇数/偶数)以确定结果是奇数(假)还是偶数(真)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM