簡體   English   中英

用C語言編寫一個程序,將輸出給定數字之間的第一項和大量數字序列的項數

[英]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編寫一個程序,該程序將取2個自然數k和m,假設k <= m,並將輸出(開始)第一個項和之間的連續連續數的最長序列的長度(項數) 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之間如何存在多個這樣的序列?

我認為可以這樣解釋作業。 考慮數字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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM