c# - 为我的计算寻找数学函数(算术级数)

标签 c# algorithm math

我认为解决方案很简单,并且可能与其他问题重复。对不起,如果这个答案会重复另一个。我无法找到解决方案,因为我不知道我在寻找什么。嗯,我有这个简单的函数来计算全部成本总和。如何简化此功能,例如在数学函数中。

public int getFullCosts ()
{
    int initialCosts = 10;
    int currentCount = 3;
    int fullCosts = 0;

    for (int i = 1; i <= currentCount; i++) {
        fullCosts += i * initialCosts;
    }

    return fullCosts;
}

最佳答案

这个函数正在计算:

fullCosts = 1*initialCosts + 2*initialCosts + ... + currentCount*initialCosts

等于:

initialCosts * (1 + 2 + ... + currentCount)

the sum of the first n natural numbers is given by (n * (n + 1))/2

initialCosts * ((currentCount + 1) * currentCount)/2

下面是我的做法:

public int sumOfFirstNInts(int n) {
    return (n * (n+1)) / 2;
}

public int getFullCosts() {
    int initialCosts = 10;
    int currentCount = 3;

    return initialCosts * sumOfFirstNInts(currentCount);
}

关于c# - 为我的计算寻找数学函数(算术级数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454659/

相关文章:

algorithm - 射线(平面)三角形交点

multithreading - 这种确保临界区不被中断的算法有什么问题?

c# - 如何使 Json.NET 成为默认的 Json 序列化程序

c# - 将 .NET 程序集编译成 x86 机器码

c# - 展开 WCF 数据服务 (OData) 的投影(选择)

c# - 绑定(bind)匿名类型以创建 BindingList

从一组 n 个球中找出有缺陷的球所需的最小权重数的算法

c# - Math.sin - 清除想法

javascript - Canvas 对齐问题

python - 如何在 SymPy 中表示复杂平面区域?