一个k(1 <= k <=80)位的十进制正整数n,我们称其为大整数。现在的问题是,请你设计一个程序,对于给出的某一个大整数,找到满足条件p3+p2
一个k(1 <= k <=80)位的十进制正整数n,我们称其为大整数。现在的问题是,请你设计一个程序,对于给出的某一个大整数,找到满足条件p3+p2+3p <= n的p的最大值。这道题应该怎么做,大家一起来讨论讨论。是不是用数组来保存大数?如果是,应该怎么求p?如果不是,又怎么求。是不是有什么技巧?
#include <stdio.h> #include <stdlib.h> int len,a[100],anslen,ans[100],lenb,b[100],lenc,c[100],tmpanslen,tmpans[100]; void Calculate() { int i,j; memset(c,0,sizeof(c)); memcpy(b,ans,sizeof(ans)); lenb=anslen; for (i=1; i<=anslen; i++) for (j=1; j<=lenb; j++) { c[i+j-1]+=(ans[i]*b[j]); c[i+j]+=(c[i+j-1]/10); c[i+j-1]%=10; } lenc=anslen+lenb; while (c[lenc]==0) lenc--; memcpy(tmpans,c,sizeof(c)); tmpanslen=lenc; memset(b,0,sizeof(b)); for (i=1; i<=anslen; i++) for (j=1; j<=lenc; j++) { b[i+j-1]+=ans[i]*c[j]; b[i+j]+=b[i+j-1]/10; b[i+j-1]%=10; } lenb=anslen+lenc; while (b[lenb]==0) lenb--; for (i=1; i<=lenb; i++) tmpans[i]+=(b[i]+ans[i]*3); tmpanslen=lenb; for (i=1; i<=tmpanslen; i++) { tmpans[i+1]+=tmpans[i]/10; tmpans[i]%=10; } if (tmpans[tmpanslen+1]) tmpanslen++; } int Biger() { if (tmpanslen>len) return 1; else if (tmpanslen<len) return 0; int i; for (i=len; i>=1; i--) if (tmpans[i]>a[i]) return 1; else if (tmpans[i]<a[i]) return 0; return 0; } int main() { int i,j; char c[100]; scanf("%s",c); len=strlen(c); for (i=len; i>=1; i--) a[i]=c[len-i]-'0'; anslen=len/3+1; memset(ans,0,sizeof(ans)); for (i=anslen; i>=1; i--) for (j=0; j<=9; j++) { ans[i]=j+1; Calculate(); if (Biger()) { ans[i]=j; break; } } while (ans[anslen]==0) anslen--; for (i=anslen; i>=1; i--) printf("%d",ans[i]); printf("\n"); system("pause"); }