前几天看生成函数的书,写了一下计算若干元分成1,2,5分计算组合的程序

lff0305 2005-10-26 09:22:34
记得有人讨论过,给的算法也很好,我写的是getCount()函数,
主要是根据生成函数的推导。计算不论n多大,2次乘法2次加法就行。
getCount1()是比较用的。
public class CaculateDime {
static long n = 0;
static int[] magic = {1,1,2,2,3,4,5,6,7,8,7,8,7,8,7,6,5,4,3,2,2,1,1};

public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
n = Long.parseLong(input.readLine());
System.out.print(" Total0:" + getCount());
System.out.println(" Total1:" + getCount1());
}
public static long getCount() {
if (0 == n) return 0;
long result = 0;
for (int i=0; i<magic.length; i++) {
if ((n - i) % 10 ==0) {
long t = (n - i) / 10;
//System.out.println(" debug :" + magic[i] + " : " + t);
result += magic[i]*(t+2)*(t+1)/2;
}
} //end for i
return result;
}
public static long getCount1() {
long result = 0;
for (int i=0; i <= n; i++) {
for (int j=0; j<=n; j++) {
if (n - i*2 - j*5 >= 0)
result++;
else
break;
} //end for j
} //end for i
return result;
}
}
...全文
96 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧