你们中的一些人可能熟悉 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 都存储在数组中,因为您以后不需要它们。
如果您使用
./yourscript
或bash script
,则无需在脚本末尾取消设置变量,因为它们会随着这 shell 实例(无论如何最好先初始化它们)。你不需要
awk
来做数学,bash
就可以了。seq
和let
并不是在 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/