swift - 试图找出欧拉项目问题 1,(求 1000 以下所有数字的总和,能被 3 整除,并且 5

标签 swift xcode

我能够在屏幕上打印出可被 3 整除的数字和 1000 以下的 5 的数字,但我不确定如何将所有数字的总和相加!请帮助我找到正确的方向,谢谢! :) 才做 swift 两天,真的很享受。但这是我的代码可能不是最漂亮的;)

import UIKit

func sumFinder (untill n : Int) {
    print (3)
    print (5)
    var num1 = 3
    var num2 = 5

    for iteration in 0...n {
        var num3 = num1 + 3
        var num4 = num2 + 5
        print(num3)
        print(num4)

        num1 = num3
        num2 = num4

       let sum = (num1 + num2 + num3 + num4)

    }


}

sumFinder(untill:1000)

最佳答案

您可以用一行完成:创建一个范围,使用 isMultiple(of 过滤项目,并使用 reduce 总结结果

func sumFinder (until n : Int) -> Int {
    return (0...n).lazy.filter{ $0.isMultiple(of: 3) && $0.isMultiple(of: 5) }.reduce(0, +)
}

sumFinder(until: 1000) // 33165

然而,Project Euler – Problem 1 中的实际挑战是

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

在本例中,结果为 234168。将 && 替换为 ||

func sumFinder (until n : Int) -> Int {
    return (0...n).lazy.filter{ $0.isMultiple(of: 3) || $0.isMultiple(of: 5) }.reduce(0, +)
}

关于swift - 试图找出欧拉项目问题 1,(求 1000 以下所有数字的总和,能被 3 整除,并且 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56725733/

相关文章:

xcode - 无法绑定(bind)到 NSOutlineView 中的 NSButton 值

ios - 全局设置 iOS 自动时间

objective-c - 快速将 UIColor 转换为 CGColor

ios - Xcode 9.4.1 上传 App Store 时缺少 App Store 图标

xcode - 使用 swift 在 OS X 中禁用 sleep 模式

ios - 不同UIApplicationMain时引用appDelegate

ios - 如何动态扩展 UITableViewCell 高度?

ios - 你能打印一些东西并根据最后的 println 做一个函数吗?

javascript - 从资源中将 javascript 加载到 UIWebView

xcode - 对于 "Working copy not locked; this is probably a bug, please report"SVN 错误我该怎么办?