ACM求助。
http://www.输出-1时需要判断多少次?10^k?
希望大牛提示一下,纠结了
#include <stdio.h> #include <string.h> #include <stdlib.h> void Mul(char *a, char *b, char *c, int k) { //求a*b后k位值,放入c中,均逆序 int Result, i, j; int a_len = strlen(a); int b_len = strlen(b); for (i = 0;i <= k;c[i++] = '\0'); for (i = 0;i < a_len && i < k;++i) for (j = 0;j < b_len && i+j < k;++j) { Result = (a[i]-'0') * (b[j]-'0') + c[i+j]; c[i+j] = Result % 10; c[i+j+1] += Result / 10; } for (i = 0;i < k;c[i++] += '0');c[i] = '\0'; } int Get(char *nn, int k) { //别的函数没问题,就是这个。。。 //我忽略了什么??? int mul = 1, i, j; char temp[101], result[101]; strcpy(temp, nn); for (i = 0;i < k;++i) { Mul(nn, temp, result, k); for (j = 1;nn[i] != result[i];++j) { if (j >= 10) return -1; strcpy(temp, result); Mul(nn, temp, result, k); } mul *= j; } return mul; } int fun(char *n, int k) { //将n后k位存入nn,并逆序 if (strcmp(n, "1") == 0 || strcmp(n, "0") == 0) return 1; int i = 0; char *p, nn[101] = {0}; for (p = n;*p;++p); for (--p;p >= n && i < k;nn[i++] = *p--); return Get(nn, k); } int main() { int k; char n[101]; while (scanf("%s%d", n, &k), n[0] != '0' && k) printf("%d\n", fun(n, k)); return 0; }
#include <stdio.h> #include <string.h> #include <stdlib.h> void Mul(char *a, char *b, char *c, int k) { int Result, i, j; int a_len = strlen(a); int b_len = strlen(b); for (i = 0;i <= k;c[i++] = '\0'); for (i = 0;i < a_len && i < k;++i) for (j = 0;j < b_len && i+j < k;++j) { Result = (a[i]-'0') * (b[j]-'0') + c[i+j]; c[i+j] = Result % 10; c[i+j+1] += Result / 10; } for (i = 0;i < k;c[i++] += '0');c[i] = '\0'; } void Mul1(char *a, int b) { int i, j, result; int len = strlen(a); char *temp = (char *)malloc(len + 2); memset(temp, 0, len+2); for (i = len-1, j = 0;i >= 0; --i, ++j) { result = (a[i]-'0') * b + temp[j]; temp[j] = result % 10; temp[j+1] = result / 10; } if (result / 10 == 0) --j; for (++i;j >= 0;a[i++] = temp[j--] + '0');a[i] = '\0'; free(temp); } char *Get(char *nn, int k) { int i, j = 0; char *mul = (char *)malloc(101);strcpy(mul, "1"); if (strcmp(nn, "1") == 0 || strcmp(nn, "0") == 0) {return mul;} char temp[101], result1[101], result2[101]; char temp1[101], temp2[101]; strcpy(temp, nn); Mul(nn, temp, result1, k); Mul(result1, temp, result2, k); for (i = 0;i < k;++i) { strcpy(temp1, temp); for (j = 1;result1[i] != result2[i];++j) { if (j >= 10) {free(mul);return NULL;} Mul(temp, temp1, temp2, k); strcpy(temp1, temp2); Mul(nn, temp1, result1, k); Mul(result1, temp1, result2, k); } strcpy(temp, temp1); Mul1(mul, j); } return mul; } char *fun(char *n, int k) { int i = 0; char *p, nn[101] = {0}; for (p = n;*p;++p); for (--p;p >= n && i < k;nn[i++] = *p--); return Get(nn, k); } int main() { int k; char n[101], *p; while (scanf("%s%d", n, &k), n[0] != '0' && k) { p = fun(n, k); printf("%s\n", p ? p : "-1"); free(p); } return 0; }