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函数:

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 ) 值来计算相应的序列和。例如:

Matlab 复制代码
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 扩展解决方案:

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

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

Matlab 复制代码
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 Problem 2909, a slightly harder variant of this problem.

(π(除以4)可以用以下无限级数近似: π/4 = 1 - 1/3 + 1/5 - 1/7 + ... 对于给定的项数(n),返回π的实际值与这个常数的近似值之间的差。 此外,尝试问题2909,这是这个问题的一个稍微更难的变体。")

Matlab 复制代码
function pi_approximation_error = computePiApproximationError(n)
    % 计算π的近似值与实际值之间的差
    
    % 初始化近似值
    pi_approximation = 0;
    
    % 循环遍历每一项
    for k = 0:n-1
        % 计算当前项的值
        term = (-1)^k / (2*k + 1);
        
        % 将当前项加到近似值中
        pi_approximation = pi_approximation + term;
    end
    
    % 计算π的近似值
    pi_approximation = 4 * pi_approximation;
    
    % 计算π的实际值
    actual_pi = pi;
    
    % 计算近似值与实际值之间的差
    pi_approximation_error = actual_pi - pi_approximation;
end

然后,你可以调用这个函数来计算给定项数的近似值与实际值之间的差,比如:

Matlab 复制代码
n = 100; % 给定的项数

pi_approximation_error = computePiApproximationError(n);
disp(pi_approximation_error); % 显示结果

这将给出近似值与实际值之间的差。至于问题2909,你可以在完成这个问题后尝试解决它。

例4

Problem 2576. Sum of series II

What is the sum of the following sequence:

复制代码
 Σ(2k-1)^2 for k=1...n

for different n?

Matlab 复制代码
function sum_sequence = calculate_sequence_sum(n)
    % 初始化总和为0
    sum_sequence = 0;
    
    % 计算序列的总和
    for k = 1:n
        sum_sequence = sum_sequence + (2*k - 1)^2;
    end
end

这个函数接受一个参数 n,代表序列的长度,并返回序列的总和。你可以调用这个函数并传入不同的 n 值来计算不同长度的序列的总和。

例5

Problem 2577. Sum of series III

What is the sum of the following sequence:

复制代码
 Σ(2k-1)^3 for k=1...n

for different n?

Matlab 复制代码
function sum_sequence = calculate_sequence_sum(n)
    % 初始化总和为0
    sum_sequence = 0;
    
    % 计算序列的总和
    for k = 1:n
        sum_sequence = sum_sequence + (2*k - 1)^3;
    end
end

这个函数接受一个参数 n,代表序列的长度,并返回序列的总和。你可以调用这个函数并传入不同的 n 值来计算不同长度的序列的总和。

例6

Problem 2578. Sum of series IV

What is the sum of the following sequence:

复制代码
 Σ(-1)^(k+1) (2k-1)^2 for k=1...n

for different n?

Matlab 复制代码
function sum_sequence = calculate_sequence_sum(n)
    % 初始化总和为0
    sum_sequence = 0;
    
    % 计算序列的总和
    for k = 1:n
        sum_sequence = sum_sequence + (-1)^(k+1) * (2*k - 1)^2;
    end
end

这个函数接受一个参数 n,代表序列的长度,并返回序列的总和。你可以调用这个函数并传入不同的 n 值来计算不同长度的序列的总和。

例7

Problem 2579. Sum of series V

What is the sum of the following sequence:

复制代码
 Σk(k+1) for k=1...n

for different n?

Matlab 复制代码
function sum_sequence = calculate_sequence_sum(n)
    % 初始化总和为0
    sum_sequence = 0;
    
    % 计算序列的总和
    for k = 1:n
        sum_sequence = sum_sequence + k*(k+1);
    end
end

这个函数接受一个参数 n,代表序列的长度,并返回序列的总和。你可以调用这个函数并传入不同的 n 值来计算不同长度的序列的总和。

例8

Problem 2580. Sum of series VI

What is the sum of the following sequence:

复制代码
 Σk⋅k! for k=1...n

for different n?

Matlab 复制代码
function sum_sequence = calculate_sequence_sum(n)
    % 初始化总和为0
    sum_sequence = 0;
    
    % 计算序列的总和
    for k = 1:n
        sum_sequence = sum_sequence + k*factorial(k);
    end
end

这个函数接受一个参数 n,代表序列的长度,并返回序列的总和。你可以调用这个函数并传入不同的 n 值来计算不同长度的序列的总和。

例9

Problem 2581. Sum of series VII

What is the sum of the following sequence:

复制代码
 Σ(km^k)/(k+m)! for k=1...n

for different n and m?

Matlab 复制代码
function sum_sequence = calculate_sequence_sum(n, m)
    % 初始化总和为0
    sum_sequence = 0;
    
    % 计算序列的总和
    for k = 1:n
        sum_sequence = sum_sequence + (k*m^k) / factorial(k+m);
    end
end

这个函数接受两个参数 n 和 m,分别代表序列的长度和 m 的值,并返回序列的总和。你可以调用这个函数并传入不同的 n 和 m 值来计算不同参数下的序列的总和。

例10

Problem 2607. Generate Square Wave

Generate a square wave of desired length, number of complete cycles and duty cycle. Here, duty cycle is defined as the fraction of a complete cycle for which the cycle is at high value. Loops are not allowed.

生成所需长度、完整周期数和占空比的方波。这里,占空比被定义为一个完整周期中处于高电平状态的时间所占比例。不允许使用循环。

你可以使用 MATLAB 的向量化方法来生成所需长度、完整周期数和占空比的方波,而不使用循环。下面是一个示例代码:

Matlab 复制代码
function square_wave = generate_square_wave(length, num_cycles, duty_cycle)
    % 计算一个完整周期的长度
    cycle_length = length / num_cycles;
    
    % 计算高电平状态的持续时间
    high_time = cycle_length * duty_cycle;
    
    % 创建时间向量
    t = linspace(0, length, length);
    
    % 生成方波信号
    square_wave = mod(t, cycle_length) < high_time;
end

这个函数接受三个参数:方波的总长度、完整周期数和占空比。它返回一个方波信号,该信号的持续时间和占空比符合给定的参数。

例11

Problem 2640. Find similar sequences

Another problem inspired by a question on the answers forum.

Given a matrix of positive integer numbers, find all the rows that are similar to the first rows and return these rows as a new matrix.

Rows are considered similar if the numbers common to both rows are in the exact same order with no other numbers in between. 0s in a row are always ignored and only occur at the end of the row.

For example:

复制代码
 [3 1 5 0 0] and [4 2 1 5 0] are similar (1 5 are the common numbers and occur in the same order)
 [3 1 5 0 0] and [3 4 1 5 0] are not similar (3 1 5 are the common numbers, there's a 4 in between)

给定一个正整数矩阵,找到所有与第一行相似的行,并将这些行作为一个新矩阵返回。

如果两行中共有的数字以完全相同的顺序出现,且中间没有其他数字,则认为它们是相似的。行中的0总是被忽略,且只出现在行的末尾。

例如:

[3 1 5 0 0] 和 [4 2 1 5 0] 是相似的(1 5 是共有的数字,且以相同的顺序出现) [3 1 5 0 0] 和 [3 4 1 5 0] 不相似(3 1 5 是共有的数字,但中间有一个 4)

可以使用 MATLAB 编写一个函数来实现这个功能。以下是一个可能的实现:

Matlab 复制代码
function similar_rows = find_similar_rows(matrix)
    % 获取矩阵的大小
    [num_rows, num_cols] = size(matrix);
    
    % 提取第一行
    first_row = matrix(1,:);
    
    % 初始化相似行矩阵
    similar_rows = [];
    
    % 遍历矩阵的每一行
    for i = 2:num_rows
        current_row = matrix(i,:);
        
        % 找到两行中共有的数字
        common_numbers = intersect(first_row(first_row~=0), current_row(current_row~=0));
        
        % 检查是否以相同顺序出现
        if isequal(common_numbers, current_row(ismember(current_row, common_numbers)))
            % 如果是相似的,则添加到相似行矩阵中
            similar_rows = [similar_rows; current_row];
        end
    end
end

你可以将这个函数应用于你的正整数矩阵,它将返回所有与第一行相似的行作为一个新矩阵。

例12

Problem 2800. arithmetic progression

I've written a program to generate the first few terms of arithmetic progressions. I've noticed something odd though, there's always one wrong term. Surely, there couldn't be a bug in my code, could it?

Can you tell me the position of the wrong term, and return the correct sequence?

For example, given

复制代码
errorsequence = [2 4 7 8 10]; %arithmetic sequence starting at 2 with increment 2

then

复制代码
errorposition = 3;
truesequence = [2 4 6 8 10]; 

我写了一个程序来生成等差数列的前几项。但我注意到了一些奇怪的地方,总是有一个错误的项。但我的代码肯定没有 bug,对吧?

你能告诉我错误项的位置,并返回正确的序列吗?

例如,给定

errorsequence = [2 4 7 8 10]; % 从 2 开始的等差数列,增量为 2 那么

errorposition = 3; truesequence = [2 4 6 8 10];

Matlab 复制代码
function [errorposition, truesequence] = find_error_term(sequence)
    % 初始化默认值
    errorposition = -1;
    truesequence = [];
    
    % 计算等差数列的公差
    d = sequence(2) - sequence(1);
    
    % 寻找错误项
    for i = 2:length(sequence)
        if sequence(i) - sequence(i-1) ~= d
            errorposition = i;
            break;
        end
    end
    
    % 构建正确的序列
    if errorposition ~= -1
        truesequence = sequence;
        truesequence(errorposition) = sequence(errorposition - 1) + d;
    end
end

你可以将这个函数应用于你的错误数列,它将返回错误项的位置以及正确的序列。

例13

Problem 2801. geometric progression

I've modified my previous program so that it now generates geometric progressions. For some reason, there's still always one wrong term. I'll blame it on my computer memory, it can't be my programming.

Once again, can you tell me the position of the wrong term, and return the correct sequence?

For example, given

复制代码
errorsequence = [2 6 18 25 162]; %geometric sequence starting at 2 with ratio of 3

then

复制代码
errorposition = 4;
truesequence = [2 6 18 54 162]; 

Note: The progression starts and ratio are integer only, so the sequence you return is expected to be made up of integers only.

我修改了之前的程序,使其现在生成几何级数。出于某种原因,总是有一个错误的项。我会归咎于我的计算机内存,肯定不是我的编程问题。

再次,请问你能告诉我错误项的位置,并返回正确的序列吗?

例如,给定

errorsequence = [2 6 18 25 162]; % 以 2 开始的几何级数,比值为 3 那么

errorposition = 4; truesequence = [2 6 18 54 162]; 注意:序列的起始项和比值都是整数,因此你返回的序列应该仅由整数组成。

Matlab 复制代码
function [errorposition, truesequence] = find_error_term_geo(sequence)
    % 初始化默认值
    errorposition = -1;
    truesequence = [];
    
    % 计算几何级数的比值
    r = sequence(2) / sequence(1);
    
    % 寻找错误项
    for i = 2:length(sequence)
        if sequence(i) / sequence(i-1) ~= r
            errorposition = i;
            break;
        end
    end
    
    % 构建正确的序列
    if errorposition ~= -1
        truesequence = sequence;
        truesequence(errorposition) = sequence(errorposition - 1) * r;
    end
end

你可以将这个函数应用于你的错误几何级数,它将返回错误项的位置以及正确的序列。

例14

Problem 2909. Approximation of Pi (vector inputs)

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.

This problem is the same as Problem 2908, except that the test suite will pass vectors for the number of terms, rather than breaking each truncated infinite series into a separate test.

以下是MATLAB程序,用于计算给定项数(n)的π/4的近似值,并返回π的实际值与这个近似值之间的差异:

Matlab 复制代码
function pi_error = calculate_pi_error(n)
    % 初始化近似值和符号
    approx_pi = 0;
    sign = 1;

    % 计算π/4的近似值
    for i = 1:n
        term = 1 / (2*i - 1);
        approx_pi = approx_pi + sign * term;
        sign = -sign;
    end

    % 计算π的实际值
    actual_pi = pi;

    % 计算误差
    pi_error = actual_pi - 4 * approx_pi;
end

你可以使用该函数来计算给定项数的π/4的近似值与π的实际值之间的差异,例如

Matlab 复制代码
n = 100; % 项数
pi_error = calculate_pi_error(n);
disp(pi_error);

这将输出π的实际值与近似值之间的差异。

例15

Problem 2910. Mersenne Primes vs. All Primes

A Mersenne prime (M) is a prime number of the form M = 2^p - 1, where p is another prime number. Problem 525 asks the user to determine if a number is a Mersenne prime. In this problem, you are tasked with returning the number of primes numbers below the input number, n, that are Mersenne primes and the fraction of all primes below that input number that the Mersenne primes represent.

For example, for n = 100, there are 25 primes numbers: 2, 3, 5, 7, ..., 89, 97. As far as Mersenne primes go, there are only three that are less than 100: 2^2 - 1 = 3, 2^3 - 1 = 7, and 2^5 - 1 = 31. The corresponding fraction would be 3/25.

以下是一个MATLAB程序,用于计算小于输入数n的质数中的梅森素数数量以及梅森素数所占的比例:

Matlab 复制代码
function [mersenne_count, mersenne_fraction] = mersenne_primes(n)
    % 计算小于n的所有质数
    primes_list = primes(n);

    % 初始化梅森素数数量
    mersenne_count = 0;

    % 遍历所有质数
    for i = 1:length(primes_list)
        % 计算2的幂减1
        mersenne = 2^primes_list(i) - 1;

        % 如果结果是质数,则增加梅森素数计数
        if isprime(mersenne)
            mersenne_count = mersenne_count + 1;
        end
    end

    % 计算梅森素数所占的比例
    mersenne_fraction = mersenne_count / length(primes_list);
end

可以使用该函数来计算小于给定数n的质数中的梅森素数数量以及梅森素数所占的比例,例如:

Matlab 复制代码
n = 100; % 输入数
[mersenne_count, mersenne_fraction] = mersenne_primes(n);
disp(['梅森素数数量:', num2str(mersenne_count)]);
disp(['梅森素数比例:', num2str(mersenne_fraction)]);

这将输出小于100的质数中的梅森素数数量以及梅森素数所占的比例。

相关推荐
阿史大杯茶38 分钟前
Codeforces Round 976 (Div. 2 ABCDE题)视频讲解
数据结构·c++·算法
2401_858120531 小时前
Spring Boot框架下的大学生就业招聘平台
java·开发语言
LluckyYH1 小时前
代码随想录Day 58|拓扑排序、dijkstra算法精讲,题目:软件构建、参加科学大会
算法·深度优先·动态规划·软件构建·图论·dfs
转调1 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
Java探秘者1 小时前
Maven下载、安装与环境配置详解:从零开始搭建高效Java开发环境
java·开发语言·数据库·spring boot·spring cloud·maven·idea
2303_812044461 小时前
Bean,看到P188没看了与maven
java·开发语言
秋夫人1 小时前
idea 同一个项目不同模块如何设置不同的jdk版本
java·开发语言·intellij-idea
不穿格子衬衫2 小时前
常用排序算法(下)
c语言·开发语言·数据结构·算法·排序算法·八大排序
萧鼎2 小时前
Python调试技巧:高效定位与修复问题
服务器·开发语言·python
wdxylb2 小时前
使用C++的OpenSSL 库实现 AES 加密和解密文件
开发语言·c++·算法