有没有关于“Anjali”被打印次数的通用公式?

Tus*_*gar 0 c iteration loops for-loop

#include <stdio.h>

int main(int argc, const char *argv[])
{
    int n;

    printf("Input a number: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i *= 3)
        for (int j = i; j <= n; j++)
            printf("Anjali \n");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试生成执行次数的公式printf()

示例:当n = 10 时;

printf()被执行20次

Eri*_*hil 5

在 中for (int i = 1; i <= n; i *= 3),对于非负整数k,i 的值为 3 k,使得 3 k \xe2\x89\xa4 n,因此k \xe2\x89\xa4 log 3 n,因此k的值为 0、1, \xe2\x80\xa6 \xe2\x8c\x8alog 3 n \xe2\x8c\x8b。(\xe2\x8c\x8a x \xe2\x8c\x8b 是x的下取整,不大于x 的最大整数。另外,我们假设n 为正数。)

\n

在外循环的每次迭代中,for (int j = i; j <= n; j++)都会执行内循环,从而导致printf执行n \xe2\x88\x92 i +1 次。在外循环的迭代中,i为 3 k,因此,在外循环的所有迭代中,printf执行 sum( n \xe2\x88\x923 k +1 for 0 \xe2\x89\xa4 k \xe2\ x89\xa4\xe2\x8c\x8alog 3 n \xe2\x8c\x8b) 次。

\n

该和为 ( n +1)\xe2\x80\xa2(\xe2\x8c\x8alog 3 n \xe2\x8c\x8b+1) \xe2\x88\x92 sum(3 k for 0 \xe2\x89\xa4 k \xe2\x89\xa4 \xe2\x8c\x8alog 3 n \xe2\x8c\x8b)。后一项是一个几何数列,其总和为 (3 \xe2\x8c\x8alog 3 n \xe2\x8c\x8b+1 \xe2\x88\x921)/(3\xe2\x88\x921)。因此printf执行 ( n +1)\xe2\x80\xa2(\xe2\x8c\x8alog 3 n \xe2\x8c\x8b+1) \xe2\x88\x92 (3 \xe2\x8c\x8alog 3 n \ xe2\x8c\x8b+1 \xe2\x88\x921)/2 次。

\n