求教1个编程题
12+23+32+43+52+63……(2n)2
unsigned foo( unsigned n ) { unsigned sum = 0; for( unsigned i=0; i!=n; ++i ) sum += (2*i+1)*(2*i+1) + (2*i+2)*(2*i+2)*(2*i+2); // 你自己加上判断sum是否溢出的逻辑 return sum; } #include <stdio.h> #include <assert.h> int main( void ) { assert( foo(0) == 0 ); assert( foo(1) == 9 ); assert( foo(2) == 82 ); assert( foo(214) == 4246907254 ); }
unsigned bar( unsigned n ) { // 你自己加上判断sum是否溢出的逻辑 unsigned lhs = n*(4*n*n-1) / 3; unsigned rhs = n*n*(n+1)*(n+1) * 2; return lhs + rhs; } #include <stdio.h> #include <assert.h> int main( void ) { assert( bar(0) == 0 ); assert( bar(1) == 9 ); assert( bar(2) == 82 ); assert( bar(214) == 4246907254 ); }