分治法在算法设计中的运用

603人阅读 评论(0)

//============================================================================
// Name        : 1～n累计和，不考虑结果溢出问题
// Author      : @CodingGeek
// Version     : 1.0
// Description : 1到n求和C代码实现
//============================================================================

#include <assert.h>

unsigned int sum1(unsigned int n)
{
if (n <= 1)
{
return n;
}
int sum = 0;
for (unsigned int i = 1; i <= n; i++)
{
sum += i;
}

return sum;
}

unsigned int sum2(unsigned int n)
{
if (n <= 1)
{
return n;
}

return n + sum2(n - 1);
}

unsigned int sum3(unsigned int n) //1到n的和为n*(n+1)/2;
{
return (n*(n+1) >> 1);
}

int main(void)
{
assert(0 == sum1(0));
assert(1 == sum1(1));
assert(55 == sum1(10));
assert(5050 == sum1(100));

assert(0 == sum2(0));
assert(1 == sum2(1));
assert(55 == sum2(10));
assert(5050 == sum2(100));

assert(0 == sum3(0));
assert(1 == sum3(1));
assert(55 == sum3(10));
assert(5050 == sum3(100));

return 0;
}

//============================================================================
// Name        : 1～n累计和，不考虑结果溢出问题
// Author      : @CodingGeek
// Version     : 1.0
// Description : 1到n求和C代码实现,Conquer and Divide分治法实现
//============================================================================

#include <assert.h>

unsigned int sum(unsigned int begin, unsigned int end)
{
if (begin == end) //递归结束条件，即分解到只有一个数求和为止
{
return begin;
}

unsigned int mid = begin + (end - begin) >> 1; //将解规模一分为二
unsigned int s1 = sum(begin, mid); //计算前半部分和
unsigned int s2 = sum(mid + 1, end); //计算后半部分和
unsigned int sum = s1 + s2;   //将前后两部分的和合并
return sum;
}

int main(void)
{
assert(0 == sum(0, 0));
assert(1 == sum(1, 1));
assert(45 == sum(1, 9));
assert(55 == sum(1, 10));
assert(5050 == sum(1, 100));
assert(12 == sum(3, 5));

return 0;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：26418次
• 积分：567
• 等级：
• 排名：千里之外
• 原创：31篇
• 转载：6篇
• 译文：0篇
• 评论：2条
评论排行
最新评论