-1

For a project, I'm trying to find the sum of the multiples of both 3 and 5 under 10,000 using Swift. Insert NoobJokes.

Printing the multiples of both 3 and 5 was fairly easy using a ForLoop, but I'm wondering how I can..."sum" all of the items that I printed.

for i in 0...10000 {
    if i % 3 == 0 || i % 5 == 0 { 
        print(i) 
    }
} 

(468 individual numbers printed; how can they be summed?)

David Makogon
  • 69,407
  • 21
  • 141
  • 189
Nate
  • 3
  • 2

6 Answers6

1

In Swift you can do it without a repeat loop:

let numberOfDivisiblesBy3And5 = (0...10000).filter{ $0 % 3 == 0 || $0 % 5 == 0 }.count

Or to get the sum of the items:

let sumOfDivisiblesBy3And5 = (0...10000).filter{ $0 % 3 == 0 || $0 % 5 == 0 }.reduce(0, {$0 + $1})
vadian
  • 274,689
  • 30
  • 353
  • 361
1

Just a little walk through about the process. First you will need a variable which can hold the value of your sum, whenever loop will get execute. You can define an optional variable of type Int or initialize it with a default value same as I have done in the first line. Every time the loop will execute, i which is either multiple of 3 or 5 will be added to the totalSum and after last iteration you ll get your result.

var totalSum = 0
for i in 0...10000 {
if i % 3 == 0 || i % 5 == 0
{
    print(i)
    totalSum = totalSum + i
}
}
print (totalSum)
Kunal Kumar
  • 1,722
  • 1
  • 17
  • 32
  • Thank you for the walkthrough! My fundamental knowledge has been improved. You are a gentleman and a scholar! – Nate Oct 25 '16 at 15:13
1

range : to specify the range of numbers for operation to act on.

here we are using filter method to filter out numbers that are multiple of 3 and 5 and then sum the filtered values. (reduce(0,+) does the job)

let sum = (3...n).filter({($0 % 3) * ($0 % 5) == 0}).reduce(0,+)
cgeek
  • 558
  • 5
  • 18
0

Try this:

var sum = 0
for i in 0...10000 {
    if i % 3 == 0 || i % 5 == 0 { 
        sum = sum + i
        print(i) 
    }
} 
print(sum)
Peter S
  • 54
  • 6
0

You just need to sum the resulting i like below

 var sum = 0

 for i in 0...10000 {
    if i % 3 == 0 || i % 5 == 0 { 

      sum = sum + i
      print(i) 
    }
} 

Now sum contains the Sum of the values

Umair Afzal
  • 4,947
  • 5
  • 25
  • 50
0

In the Bottom line, this should to be working.

var sum = 0
for i in 0...10000 {
    if i % 3 == 0 || i % 5 == 0 { 
        sum += i
        print(i)
    }
} 
print(sum)
Asaf Baibekov
  • 313
  • 1
  • 5
  • 15