CODE[VS]-数的计算-递推-天梯白银

题目描述 Description

  我们要求找出具有下列性质数的个数(包含输入的自然数n):
  先输入一个自然数n(n<=1000),然后对此自然数按照如下方法进行处理:
  1.不作任何处理;
  2.在它的左边加上一个自然数,但该自然数不能超过原数的一半;
  3.加上数后,继续按此规则进行处理,直到不能再加自然数为止.
 输入输出格式 Input/output
输入格式:
一个自然数n(n<=1000)
输出格式:
一个整数,表示具有该性质数的个数。
 输入输出样例 Sample input/output
样例测试点#1

输入样例:

6

输出样例:

6

思路:这题可以单纯地用模拟来做,但是这会比较麻烦,不如考虑用递推来做更快

要用递推肯定要先求出递推公式,随便代入几个数据就可以发现规律如下图所示:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAA/QAAAA/CAIAAADBgBTfAAANb0lEQVR4nO2d2YHiOhBFSYuESIdsCKbpjqX6w+BN8gI+ZZese/7ejHs4T0JV14vcFzMzs5/fPysBebLIk0WeLPJkkSeLPFnkySJPlrI8L2Z2EUIIIYQQQhSOmV1+fv+O1hBCCCGEEEJs5ef3r7tyf+x9hJXIk0WeLPJkkSeLPFnkySJPFnmyFOHZ5nmFexfkySJPFnmyyJNFnizyZJEnizxBFO59kSeLPFnkySJPFnmyyJNFnizyBFG490WeLPJkkSeLPFnkySJPFnmyyBNE4d4XebLIk0WeLPJkkSeLPFnkySJPEIV7X+TJIk8WebLIk0WeLPJkkSeLPEHgcP+8Xy8Drvfn+p9+3IY/fLk9Zry3eO6GPFnkySJPFnmyyJNFnizyZJEniEe4n47k3L9UxOCaPGnkySJPFnmyyJNFnizyZJEnyBHh/nFbcUl/13A/uOGAnJu88fgSPG4f3hFZAeo5un9Dulbp2ed5v5KmdXs2twrjz3tEz/kqRFVUeSZsWlkVeK6q6gHm/VSeb7ZWqgo8R6KOns0H2J7h/vXwzYLwfuE+eZQodCh52cYN98mzVahufZ4D8Nmv2bP5BqDn8rV4zs8vWFHl+fWRWc7uuaqqB5j3U3mOjt5Sqc7umRedMtno2fzjtu9jOc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HC6OOWkQl3svR5Sf0Yer07Zfuaw33MO4rzt+mxDqVw30B9Cfw82Q7lGe7JDuU2nnCH8vTEOlTl4T43aBF/WUyf6OEe3ko5hAx5xTxO0Cfilft85UGvj0LjmTeN+8y9V7Ynw32iF/Ckrge9xb/BNeSBHUrh3tAO5Rvyjv8lVsOPXjViEa/c4x1q35N5PXP/Ja+Tz/e4wbdsqwv3o+GkYU/q0i3p4TYCjokY7jOrJvN+kk24zTs88+y8+72RH533wSyzr6Gh15HXiHqGJ7JDKdyzHcr7pI7qUJWHe7xD7Tjv38+8wn3mXW6RNlqlRA73E2+TDRmeMrcUA7+y803McJ+/QRtzHWVvJUc7CTEz19+25Trvkd5CM8Tnsr15hyeuQ/l6fnDMAm6ecIdyHU+wQ+0y7w0xwz3cofae9293z19qD/dmxl9qfMGPpw+1euLvwHxR53h2nTPcYw8jnH69QfXzHu5Z9j5u0X6XeUc6VJ3fTz/8PZkOpfFsoDrUjvO+6YzOOdz7IE8WebLIk0WeLPJkkSeLPFnkyVKEp8K9L/JkkSeLPFnkySJPFnmyyJNFniAK977Ik0WeLPJkkSeLPFnkySJPFnmCKNz7Ik8WebLIk0WeLPJkkSeLPFnkCZIJ90IIIYQQQohyMbPLz+/f0RpCCCGEEEKIrfz8/r3uMvz8/h14H2E98mSRJ4s8WeTJIk8WebLIk0WeLGV5/gOok/hDBkJMfQAAAABJRU5ErkJggg==" alt="" width="772" height="48" />

从这张表可以发现,对于奇数的i,a[i]的值是和前面的偶数的a[i]值是一样的,所以得到公式①:a[i]=a[i-1](i%2==1)

那么对于偶数呢?这就可能有点小难度了,通过观察a[i]这一行可以发现,任何一个值都能在前面找到两个数使得这两个数相加恰好等于这个值,那么是不是这样呢?如果是那两个值的下标i是固定的算法么?

举个栗子:如果i=6,对应的a[i]=6,从前面的值开始找,6=2+4,a[i]值为2的i=6/2,a[i]值为4的i=6-1,从这里基本就可以得到公式②:a[i]=a[i-1]+a[i/2](i%2==0)

再举个栗子验证一下:如果i=10,那么i/2,i-1对应的a[i]值为4、6,4+6=10,所以我们就可以认定这个就是正确的递推公式了^_^

首先对于数组进行初始化处理,这里我的i是从3开始循环的,a[1]=1,a[2]=2,然后就可以开始用循环了,记得要分情况讨论(奇数偶数是不一样的公式)

代码如下:

 #include <stdio.h>
int main()
{
int a[]={},n,i;
scanf("%d",&n);
a[]=;
a[]=;
for(i=;i<=n;i++)
{
if(i%==)
{
a[i]=a[i-];
}
else
{
a[i]=a[i-]+a[i/];//递推公式
}
}
printf("%d\n",a[n]);
return ;
}
上一篇:IO流的应用————小型资源管理器


下一篇:如何安装CocoaPods