【问题标题】:Write a program in C that will output the first term and the number of terms of the sequence of abundant numbers between given numbers用 C 语言编写一个程序,输出给定数之间的丰富数序列的第一项和项数
【发布时间】:2016-12-24 07:59:03
【问题描述】:

一个丰富的数是一个自然数,其因数之和大于该数本身。我必须用 C 编写一个程序,它将采用 2 个自然数 k 和 m,假设 k (开始)第一项 和长度(项数) k 和 m 之间连续丰富数的最长序列,包括这两个数。 如果存在多个这样的长度相同的序列,那么它必须输出最小的开头。 如果这样的序列不存在,那么它必须输出方便的消息。

对不起我的英语,我希望一切都清楚。所以我需要粗体部分的帮助。这是我到目前为止所做的:

int main(void) {

    int k,m,i,j,counter=0,sum;
    scanf("%d", &k);
    scanf("%d", &m);

    for(i=k; i<=m; i++) {
        sum=0;
        for(j=1; j<i; j++) {
            if(i%j==0) sum=sum+j;
        }
        if(i<sum) {
                counter++;
                printf("%d\n", i);

        }
    }

    if(counter==0) printf("There aren't any abundant numbers!");
    else printf("%d", counter);
    return 0;
}

当我只需要第一项时,这会输出 k 和 m 之间的所有丰富数。至于这个:如果存在多个这样的长度相同的序列,那么它必须输出最小的开头,我什至不明白他们的意思。 k和m之间怎么可能存在不止一个这样的序列?

【问题讨论】:

  • 请显示示例输入及其预期输出!

标签: c algorithm math numbers


【解决方案1】:

我认为作业可以这样解释。考虑一个数字 N。

N not abundant 
N+1 abundant 
N+2 abundant 
N+3 abundant 
N+4 not abundant 

所以这里你有一个由 3 个丰富的数字组成的序列,所以你必须输出 3 的长度和 N+1 的数字。

所以你需要跟踪序列长度和序列的起始编号。

int current_sequence_length = 0; // Increment when you find an abundant number
                                 // Set to zero when you find a not abundant number

int current_sequence_start = 0;  // Set to the number that starts a new sequence

那么你需要跟踪最长的序列所以你需要:

int longest_sequence_length = 0;

int longest_sequence_start = 0;

每当一个序列结束时,你必须这样做:

if (current_sequence_length > longest_sequence_length)
{
    longest_sequence_length = current_sequence_length;
    longest_sequence_start = current_sequence_start;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-04
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多