java - 读取 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(....)
解决方案
简而言之,您需要将 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);
推荐阅读
- c++ - std::set 插入器不尊重自定义比较器。(可能的编译器错误?)
- javascript - 使用 Javascript 预设 CAtiveForm 中的值
- mp4 - 计算 GOP 大小 MP4
- database - 需要一些建议来开发使用离线数据库的桌面应用程序
- datepicker - Material UI 日期选择器 日期格式 React
- python - 在标准输入中跟踪行号的 Pythonic 方法
- javascript - Vue 从对象中移除所有类原型方法
- spring-boot - spring data jpa中创建或更新的Cascade类型是什么
- c++ - 在 C++ 中刷新字符串流时会发生什么?
- powerapps - 在共享点列表中使用搜索文本框 >500 个项目