k方和的使用

本文介绍了一种计算复杂多重循环执行次数的方法,通过数学公式推导,能够快速准确地计算出任意层数循环的执行次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有这样一个问题:

for(int i=0;i<n;i++)
   for(int j=0;j<i;j++)
     for(int k=0;k<j;k++) 
        ;
执行的次数,当然通过程序可以计算出来,不过计算出来的数字是毫无意义的,因为n改变了又得重新计算.

下面根据k方和公司给出一个方法,即使是4次循环或者5次循环都可以计算.

这里设定 f(n,k) 表示 n的k次方法和(∑i^k) ,通过计算得出
f(n,1)=1+2+3+4+...+n = 1/2 n^2 +1/2 * n
f(n,2)=1^2+2^2+.....+n^2= 1/3 n^3 + 1/2 n^2 +1/6 * n
f(n,3)=1^3+2^3+....+n^3=  1/4 n^4 + 1/2 n^3 + 1/4 n^2
....

上面的问题:
f(1,1)+f(2,1)+f(3,1)+...f(n,1)
=∑f(i,1) (i从1到n)
=∑i(i+1)/2  (1->n)
=∑(i^2/2 + i/2) (1-->n)
=(1/2)∑(i^2) + (1/2)∑(i)   (1-->n)
=(1/2)f(n,2)+(1/2)f(n,1)
=n(n+1)(2n+1)/12+ n(n+1)/4
=(1/6)*n*(n+1)(n+2)

 

 

 

 

 

C#简单变色龙游戏 /// /// 创建一副52张的新牌 /// /// public static System.Collections.ArrayList Creat() { System.Collections.ArrayList list = new System.Collections.ArrayList(); for (int i = 3; i <= 6; i++) { for (int j = 1; j <= 13; j++) { Poker p = new Poker(); switch (j) { case 1: p = new Poker((PokerStyle)i, "A", j, 11); break; case 2: p = new Poker((PokerStyle)i, j.ToString(), j, 10); break; case 11: p = new Poker((PokerStyle)i, "J", j, 11); break; case 12: p = new Poker((PokerStyle)i, "Q", j, 2); break; case 13: p = new Poker((PokerStyle)i, "K", j, 3); break; default: p = new Poker((PokerStyle)i, j.ToString(), j, j); break; } list.Add(p); } } return list; } /// /// 洗牌 /// /// /// public static System.Collections.ArrayList shuffle(System.Collections.ArrayList list)//洗牌 { System.Random r = new Random(); for (int i = 0; i <= 7; i++) { int rightOrRight = r.Next(1, 3); Poker[] leftPoker = new Poker[list.Count / 2]; Poker[] rightPoker = new Poker[list.Count % 2 == 0 ? list.Count / 2 : list.Count / 2 + 1]; list.CopyTo(0, leftPoker, 0, list.Count / 2); list.CopyTo(list.Count / 2, rightPoker, 0, list.Count % 2 == 0 ? list.Count / 2 : list.Count / 2 + 1); if (rightOrRight == 1)//左边插右边 { list.Clear(); for (int j = 0; j <= leftPoker.Length - 1; j++) { list.Add(rightPoker[j]); list.Add(leftPoker[j]); } if (leftPoker.Length != rightPoker.Length) { list.Add(rightPoker[rightPoker.Length - 1]); } } else { list.Clear(); for (int j = 0; j <= leftPoker.Length - 1; j++) { list.Add(leftPoker[j]); list.Add(rightPoker[j]); } if (leftPoker.Length != rightPoker.Length) { list.Add(rightPoker[rightPoker.Length - 1]); } } } return list; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值