首页 > 解决方案 > 读取 n,求 M 的值,其中 M = 2 * 4 * 6 * … * ≤ n

问题描述

n是用户给定的任何整数值。M是 中所有偶数的乘积 1..n

M = 2 * 4 * 6 * … * ≤ n

例子 :

int n = 9

输出

 int output = 2*4*6*8; // 384

我的代码:

Scanner in = new Scanner(System.in)

int n=inut.nextInt();

for(....)

标签: javafor-loop

解决方案


简而言之,您需要将 1 和 n 之间的所有偶数相乘。

为此,您可以使用 for 循环和 if 语句。for-loop 将为您提供 1..n 之间的所有数字,并且 if 语句将拒绝奇数,只留下偶数。

最后一条路径是将所有值相乘。

int n = 9;// input;

int result = 1; // because you are multiplying, initial result must be 1
for (int i = 1; i <= n; i++) {
   if (i % 2 == 0) { // ignore all odd numbers
      result *= i; // multiply result with next even value
   }
}
System.out.println(result); // print the result: 384

您可以将其视为装配线。一开始,有人正在生成从 1 到 n 的数字。然后有人称为“过滤器”拒绝(推送到垃圾)所有奇数,在行尾有人称为“聚合器”将所有值乘以结果。

对于 Java 8 和流,这可以表示为:

  int result = IntStream.range(1,n)// generate numbers from 1 to n
               .filter(value->value%2==0) // reject all odd numbers
               .reduce(1, (a,b)-> a*b); // multiple all values, with 1 as initial result
  System.out.println(result);

推荐阅读