Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Tổng bình phương n số lẻ đầu tiên


Chuỗi bình phương các số lẻ đầu tiên: 1, 9, 25, 49, 81, 121... Hay 1², 3², 5², 7², 9², 11²...

Công thức tổng: n(2n+1)(2n-1)/3 = n(4n² - 1)/3

Ví dụ:

Input: N = 4 Output: sum = 84

Giải thích

1² + 3² + 5² + 7² = 1 + 9 + 25 + 49 = 84

Áp dụng công thức: sum = 4(4*4² - 1)/3 = 4(64-1)/3 = 4*63/3 = 4*21 = 84. Cách dùng công thức tốt hơn vì không dùng vòng lặp, giảm độ phức tạp thời gian.

Ví dụ (vòng lặp)

#include <stdio.h>
int main() {
    int n = 8;
    int sum = 0;
    for (int i = 1; i <= n; i++)
        sum += (2*i - 1) * (2*i - 1);
    printf("The sum of square of first %d odd numbers is %d",n, sum);
    return 0;
}

Kết quả

The sum of square of first 8 odd numbers is 680

Ví dụ (công thức)

#include <stdio.h>
int main() {
    int n = 18;
    int sum = ((n*((4*n*n)-1))/3);
    printf("The sum of square of first %d odd numbers is %d",n, sum);
    return 0;
}

Kết quả

The sum of square of first 18 odd numbers is 7770