bash - 在 bash 中解决一个(简单的)数字练习

标签 bash math

你们中的一些人可能熟悉 Project Euler,我目前正在尝试他们的一些问题来自学更多 bash。它们比“script-y”更具数学性,但它有助于语法等。

目前要我解决的问题:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

我的代码是这样的:

#!/bin/bash

i="1"

for i in `seq 1 333`
do
    threes[$i]=`calc $i*3` # where 'calc' is a function written in bashrc
    #calc actually looks like: calc() {awk "BEGIN { print "$*"} }

    let "sumthrees = sumthrees + ${threes[$i]}"
done

for i in `seq 1 199`
do
    fives[$i]=`calc $i*5`
    let "sumfives = sumfives + ${fives[$i]}"
done

let "ans = $sumfives + $sumthrees"

echo "The sum of all 3 factors is $sumthrees and the sum of all five factors is $sumfives"
echo "The sum of both is $ans"

#So I can repeatedly run the script without bash remembering the variables between executions
unset i
unset fives
unset threes
unset sumfives
unset sumthrees
unset ans

到目前为止,我还没有得到正确的答案,但我已经想不出哪里出错了。 (仅供引用,该脚本目前给我 266333,我认为这很接近,但我还不知道答案。)

有人能发现什么吗?对于我自己的学习,如果人们可能愿意分享更优雅的解决方案,那就太好了。

编辑

感谢您提供的所有答案,内容非常丰富。由于这里有很多有用的答案,我将接受我最喜欢的答案作为正确的主题答案。

最佳答案

  • Blue Moon 指出了您逻辑上的实际问题。

  • 您不需要将所有的 3 和 5 都存储在数组中,因为您以后不需要它们。

  • 如果您使用 ./yourscriptbash script,则无需在脚本末尾取消设置变量,因为它们会随着这 shell 实例(无论如何最好先初始化它们)。

  • 你不需要 awk 来做数学,bash 就可以了。

  • seqlet 并不是在 bash 脚本中执行任何操作的最佳方式。

这是一个简单的版本:

#!/bin/bash
sum=0
for ((i=1; i<1000; i++))
do
  if (( i%3 == 0 || i%5 == 0 ))
  then
    (( sum += i ))
  fi
done
echo "$sum"

关于bash - 在 bash 中解决一个(简单的)数字练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29241612/

相关文章:

java - 将源代码转换为 LaTeX

algorithm - 从 n 个元素的数组中找到 2 个子数组,这些元素的总和等于或接近

algorithm - 如何根据赛车游戏的完成时间公平地分配一定数量的奖励积分给赛车游戏的玩家

linux - (Bash) 如何监控目录中的文件更改(创建、删除、重命名)

php - 无法以完全权限运行 shell 脚本 (UNIX)

windows - Bash on Ubuntu on Windows 启动参数

javascript - P5.js 用矩形绘制圆形

linux - 为什么 echo -n "100"| wc -c 输出 3?

linux - 如何用 Linux Bash 指令替换文件的特殊字符行?

c++ - C++ 中正弦、余弦和平方根的最快实现(不需要非常准确)