อนุกรมกำลังสองของ n เลขคี่แรก: 1, 9, 25, 49, 81, 121... เขียนได้เป็น 1^2, 3^2, 5^2, 7^2, 9^2, 11^2...
สูตรคณิตศาสตร์: n(2n+1)(2n-1)/3 = n(4n^2 - 1)/3
ตัวอย่าง:
Input: N = 4 Output: sum = 84
คำอธิบาย
1^2 + 3^2 + 5^2 + 7^2 = 1 + 9 + 25 + 49 = 84
ใช้สูตร: 4*(4*4^2 - 1)/3 = 4*(64-1)/3 = 4*63/3 = 4*21 = 84 ทั้ง 2 วิธีถูกต้อง แต่วิธีสูตรเร็วกว่า O(1)
ตัวอย่าง (Loop)
#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;
}ผลลัพธ์
The sum of square of first 8 odd numbers is 680
ตัวอย่าง (สูตร)
#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;
}ผลลัพธ์
The sum of square of first 18 odd numbers is 7770