最有效的方法来快速计算(简单数学)

时间:2015-06-25 16:36:14

标签: ios iphone swift swift2

问题与计算货币增长有关。

循环这n次,让我们说你从$ 50k开始,你的乘数是2.像b * 2 + a

这是正确的结果:

$50,000.00
$100,000.00
$250,000.00
$600,000.00
$1,450,000.00
$3,500,000.00
$8,450,000.00
$20,400,000.00
$49,250,000.00

所以要明确一点,问题是关于快速的效率,而不仅仅是如何计算这个。是否有任何方便的数据结构可以加快速度?基本上我只是循环多少年(n)添加2(200%)并递增一些临时变量来跟踪当前和以前的值。感觉必须有一个更好的方法来处理这个问题。

$50k base

$50k * 2 + 0 (previous value) = $100k
$100k * 2 + $50k = $250k
$250k * 2 + $100k = $600k
etc.

代码:

let baseAmount = 50000.0
let percentReturn = 200.0
let years = 10

// Calc decimal of percent.
var out: Double = 0.0
var previous: Double = 0.0
let returnPercent = percentReturn * 0.01

// Create tmp array to store values.
var tmpArray = [Double]()

// Loop through years.
for var index = 0; index < years; ++index
{
    if index == 0
    {
        out = baseAmount
        tmpArray.append(baseAmount)
    }
    else if index == 1
    {
        out = (out * returnPercent)
        tmpArray.append(out)
        previous = baseAmount
    }
    else
    {
        let tmp = (tmpArray.last! * returnPercent) + previous
        previous = tmpArray.last!
        tmpArray.append(tmp)
    }
}

println(tmpArray)

2 个答案:

答案 0 :(得分:1)

Here are some ideas for improving efficiency: Initialize your array to the appropriate size (it isn't dynamic; it is always the number of years) Remove special cases (year 0 and 1 calculations) from the for-loop Code: func calculate(baseAmount: Double, percentReturn: Double, years: Int) -> [Double] { // I prefer to return an empty array instead of nil // so that you don't have to check for nil later if years < 1 { return [Double]() } let percentReturnAsDecimal = percentReturn * 0.01 // You know the size of the array, no need to append var result = [Double](count: years, repeatedValue: 0.0) result[0] = baseAmount // No need to do this in the loop if years > 1 { result[1] = baseAmount * percentReturnAsDecimal } // Loop through years 2+ for year in 2 ..< years { let lastYear = result[year - 1] let yearBeforeLast = result[year - 2] result[year] = (lastYear * percentReturnAsDecimal) + yearBeforeLast } return result }

答案 1 :(得分:1)

速度方面的效率我发现这是算法的最快实现:

let baseAmount = 50000.0
let returnPercent = 2.0
let years = 10

// you know the size of the array so you don't have to append to it and just use the subscript which is much faster
var array = [Double](count: years, repeatedValue: 0)
var previousValue = 0.0
var currentValue = baseAmount

for i in 0..<years {
    array[i] = currentValue
    let p2 = currentValue
    currentValue = currentValue * returnPercent + previousValue
    previousValue = p2
}

print(array)