|
class temp |
|
|
数学公式该让用吧1+2+···+n |
|
|
高斯的想法: N*(N+1)/2
|
|
| 20分 |
把这处cout<<temp::GetSum<<endl;改为cout<<temp::GetSum()<<endl;就可以了;
这个cout<<temp::GetSum<<endl;输出的是函数地址,这个temp::GetSum()才是调用函数等到的值 |
|
if else 什么的用 && || 代替就好了。
unsigned int mul(unsigned int a,unsigned int b)
{
unsigned int r=0;
a&&b&&(r=a+mul(a,b-1));
return r;
}
unsigned int sum(unsigned int n)
{
return mul(n+1,n)>>1;
}
|
|
|
class temp
{ public: temp(void) { ++n; m += n; } static int AddTo(int n) protected: int temp::n = 0; int main(void) |
|
|
又优化了下乘法 unsigned int mul(unsigned int a,unsigned int b)
{
unsigned int r=0;
b&1&&(r=a);
b>>1&&(r+=mul2(a<<1,b>>1));
return r;
}
|
|
|
改一下,有个地方没改 unsigned int mul(unsigned int a,unsigned int b)
{
unsigned int r=0;
b&1&&(r=a);
b>>1&&(r+=mul(a<<1,b>>1));
return r;
}
|
|
|
这样可好:
int add(int n)
{
n && (n+=add(n - 1));
return n;
}
|
|
高斯会用到乘除 |
|
|
小试把
# include <iostream>
using namespace std;
template <int N>
struct foo
{
static int const value = foo<N - 1>::value + N;
};
template <>
struct foo<0>
{
static int const value = 0;
};
int main()
{
cout << foo<100>::value << endl;
return 0;
}
|
|
|
纯C非递归实现
#include <stdio.h>
#include <setjmp.h>
#include <limits.h>
#define SIGN(v) -(int)((unsigned int)(v) >> (sizeof(int) * CHAR_BIT - 1))
jmp_buf j;
typedef void (*FP)();
void brk() { }
void jmp() { longjmp(j, 1); }
FP jmptar[2] = { jmp, brk };
int main(void)
{
int n, sum = 0;
scanf("%d", &n);
setjmp(j);
sum += n--;
jmptar[-SIGN(n)]();
printf("%d", sum);
}
|
|
|
让编译器来做循环
template<int N> struct sum{
static const int value = N+sum<N-1>::value;
};
template<> struct sum<0>{
static const int value =0;
};
int main()
{
cout<<sum<100>::value<<endl;
return 0;
}
|
|
|
楼上模板元编程
|
|
|
剑指offer的题。。。。。。。。。,感觉没啥意思,一不考算法,二不考语言。。。
|
|