To reduce the verbosity, which was set to default 1, during compilation, I've created a Bash alias compile(c) a Nim source and run(-r) it but set the default verbosity level to 0. You will see nimc alias being used in the subsequent examples.
alias nimc='nim c -r --verbosity:0'
First, let's loop from 1 till 999 and print all the number. Type the below code
and save it as p1.nim.
for i in 1..999:
echo i
Compile and run it. You should see an output as shown.
$ nimc p1.nim
1
2
......
998
999
Next, we filter and print only number which are either a multiples of 3 or 5.
for i in 1..999:
if i mod 3 == 0 or i mod 5 == 0:
echo i
Compile and run it again.
$ nimc p1.nim
3
5
......
996
999
Lastly, to find the sum of all numbers which are the multiple of 3 or 5 below 1000.
var
sum: int;
for i in 1..999:
if i mod 3 == 0 or i mod 5 == 0:
sum = sum + i
echo sum
assert(sum == 233168)
Alternately, a different solution using Arrays.
type
IntArray = array[1..999, int]
var
total = 0
x: IntArray
for i in low(x)..high(x):
if i mod 3 == 0 or i mod 5 == 0:
total += i
echo total
assert(total == 233168)
Result of the both solutions.
$ nimc p1.nim
233168
233168
No comments:
Post a Comment