|
Friend number | ||||||
| ||||||
|
Description | ||||||
|
Friend number are defined recursively as follows. (1) numbers 1 and 2 are friend number; (2) if a and b are friend numbers, so is ab+a+b; (3) only the numbers defined in (1) and (2) are friend number. Now your task is to judge whether an integer is a friend number.
| ||||||
|
Input | ||||||
|
There are multiple test cases. For each test case: Line 1: A nonnegative integer a, 0<=a<=2^30.
| ||||||
|
Output | ||||||
|
For each test case, output one line, if a is a friend number, output "YES!", otherwise output "NO!". | ||||||
|
Sample Input | ||||||
|
3 13121 12131 | ||||||
|
Sample Output | ||||||
|
YES! YES! NO! | ||||||
|
Source | ||||||
|
ACM-ICPC黑龙江省第九届大学生程序设计竞赛选拔赛(2) |
思路:根据因式分解,ab+a+b=(a+1)*(b+1)-1
对于基础数1、2.那么这样一个数也一定是friend number:(1+1)(【(1+1)(1+1)-1】+1)-1=(1+1)(1+1)(1+1)-1。
那么:(1+2)(【(1+2)*(1+1)-1】+1)=(1+2)(1*2)(1+1)-1也是一个friend number。
其实一直这样枚举下去不难发现,如果是 friend number,这个数+1一定是由2或者是3乘叠起来的一个数,那么我们可以对一个数先加一,然后讨论这个数如果能拆分出2这个因子,那么就除2,如果不能再拆出2了,就拆3,一直拆到最后如果拆成1了,辣么就是一个friend number。
我们拿出第二组样例试一试:
13131:
13131+1=13132
13132%2==0 n=13132/2=6561
6561%3==0 n=6561/3=2187
2187%3==0 n=2187/3=729
........
n=1,那么这个数就是friend number,同理,大家可以手算一下第三组样例。
AC代码:
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
int n;
while(~scanf("%d",&n))
{
if(n==0)
{
printf("NO!\n");
continue;
}
n=n+1;
while(1)
{
if(n%2==0)
n/=2;
else break;
}
while(1)
{
if(n%3==0)
n/=3;
else break;
}
if(n==1)
printf("YES!\n");
else printf("NO!\n");
}
}

本文介绍了一种通过递归定义的Friend Number,并提供了一个简单的算法来判断一个整数是否属于此类特殊的数字。通过对输入数字进行特定的因式分解操作,可以有效地解决这一问题。
19万+

被折叠的 条评论
为什么被折叠?



