MATLAB--Sequences & Series II

Problem 2575. Sum of series I

What is the sum of the following sequence:(这个序列的和是多少:)

 Σ(2k-1) for k=1...n

for different n?(对于不同的 ( n )?)

在MATLAB中,可以使用循环来计算这个序列的和。以下是一个计算这个序列和的MATLAB函数:

function sequenceSum = sumOfSequence(n)
    % Initialize sum
    sequenceSum = 0;
    
    % Loop from k=1 to n
    for k = 1:n
        % Add (2k-1) to the sum
        sequenceSum = sequenceSum + (2*k - 1);
    end
end

 你可以调用这个函数,传入不同的 ( n ) 值来计算相应的序列和。例如:

n1 = 5;
sum1 = sumOfSequence(n1);
disp(sum1);

n2 = 10;
sum2 = sumOfSequence(n2);
disp(sum2);

这将输出对应 ( n ) 值的序列和。

例2

Problem 2672. Largest Geometric Series

Extension of Ned Gulley's wonderful Problem 317.

In a geometric series, ratio of adjacent elements is always a constant value. For example, [2 6 18 54] is a geometric series with a constant adjacent-element ratio of 3.

A vector will be given. Find the largest geometric series that can be formed from the vector.

Example:

input = [2 4 8 16 1000 2000];

output = [2 4 8 16];

Update - Test case added on 21/8/22

(Ned Gulley的问题317的扩展。

在一个几何级数中,相邻元素的比值始终是一个恒定值。例如,[2 6 18 54] 是一个几何级数,其相邻元素比值恒定为3。

将给出一个向量。找出可以从该向量中形成的最大几何级数。

例子: input = [2 4 8 16 1000 2000]; output = [2 4 8 16]; 更新 - 测试用例添加于21/8/22)

以下是这个问题的 MATLAB 扩展解决方案:

function maxGeometricSequence = findMaxGeometricSequence(input)
    % 初始化最大几何级数
    maxGeometricSequence = [];
    
    % 遍历输入向量的每个元素作为可能的起始点
    for i = 1:length(input)
        % 初始化当前可能的几何级数
        currentSequence = input(i);
        ratio = 0;
        
        % 遍历从当前起始点开始的可能的几何级数
        for j = i+1:length(input)
            % 计算相邻元素的比值
            if input(j-1) ~= 0
                ratio = input(j) / input(j-1);
            else
                break; % 避免除以0的情况
            end
            
            % 如果当前元素符合几何级数的条件,则将其添加到当前序列中
            if input(j) == input(j-1) * ratio
                currentSequence = [currentSequence, input(j)];
            else
                break; % 如果不符合条件,则终止当前序列的构建
            end
        end
        
        % 更新最大几何级数
        if length(currentSequence) > length(maxGeometricSequence)
            maxGeometricSequence = currentSequence;
        end
    end
end

 可以使用这个函数来测试:

input = [2 4 8 16 1000 2000];
output = findMaxGeometricSequence(input);
disp(output)

这应该会输出 [2 4 8 16],这是从输入向量中找到的最大几何级数。

例3

Problem 2908. Approximation of Pi

Pi (divided by 4) can be approximated by the following infinite series:

pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...

For a given number of terms (n), return the difference between the actual value of pi and this approximation of the constant.

Also, try

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值