• 主页

##### free函数如何正确使用，求大神解答。。

It was said that when testing the first computer designed by von Neumann, people gave the following problem to both the legendary professor and the new computer: If the 4th digit of 2^n is 7, what is the smallest n? The machine and von Neumann began computing at the same moment, and von Neumann gave the answer first.

Now you are challenged with a similar but more complicated problem: If the K-th digit of M^n is 7, what is the smallest n?

Input

Each case is given in a line with 2 numbers: K and M (< 1,000).

Output

For each test case, please output in a line the smallest n.

You can assume:

The answer is no more than 100.
Sample Input

3 2
4 2
4 3
Sample Output

15
21
11

``````
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void reverse(char *s)
{
int len = strlen(s);
int i, j;
char c;
for (i = 0, j = len - 1; i < j; i++, j--)
{
c = *(s + i);
*(s + i) = *(s + j);
*(s + j) = c;
}
}

char *appendTailZero(char *s, int zeros)
{
int i, len = strlen(s);
char *r = malloc(len + zeros + 1);
for (i = 0; i < len; i++)
*(r + i) = *(s + i);
for (i = len; i < len + zeros; i++)
*(r + i) = '0';
*(r + len + zeros) = '\0';
return r;
}

{
int l1 = strlen(s1);
int l2 = strlen(s2);
int len = l1 > l2 ? l1 : l2;
char *r = malloc(len + 2);
int i, prev = 0, a, b, sum;
for (i = 0; i < len; i++)
{
a = l1 - 1 - i >= 0 ? *(s1 + l1 - 1 - i) - '0' : 0;
b = l2 - 1 - i >= 0 ? *(s2 + l2 - 1 - i) - '0' : 0;
sum = a + b + prev;
*(r + i) = sum > 9 ? sum - 10 + '0' : sum + '0';
prev = sum > 9 ? 1 : 0;
}
if (prev)
{
*(r + len) = '1';
*(r + len + 1) = '\0';
}
else
*(r + len) = '\0';
reverse(r);
return r;
}

char *multiplyHelper(char *s1, int digit)
{
int i, res, prev = 0, len = strlen(s1);
char *r = malloc(len + 2);
if (!digit)
{
*r = '0';
*(r + 1) = '\0';
return r;
}

for (i = 0; i < len; i++)
{
res = (*(s1 + len - 1 - i) - '0') * digit + prev;
*(r + i) = res % 10 + '0';
prev = res / 10;
}
if (prev)
{
*(r + len) = prev + '0';
*(r + len + 1) = '\0';
}
else
*(r + len) = '\0';
reverse(r);
return r;
}

char *multiply(char *s1, char *s2)
{
if (strlen(s1) < strlen(s2))
{
char *temp;
temp = s1;
s1 = s2;
s2 = temp;
}
int l2 = strlen(s2);
int i;
char *t, *zt;
char *sum = malloc(2);
char *tp;
sum = "0";
for (i = 0; i < l2; i++)
{
tp = sum;
t = multiplyHelper(s1, *(s2 + l2 - 1 - i) - '0');
zt = appendTailZero(t, i);
free(t);
free(zt);
free(tp);//加入这行代码提交就报Runtime Error, 不加就Accepted,但是内存占用很大
}
return sum;
}

int main()
{
int k;
char m[5];
while (scanf("%d %s", &k, m) != EOF)
{
char *r = m;
int count = 1;
while (strlen(r) < k)
{
r = multiply(r, m);
count++;
}
r = r + strlen(r) - k;
while (*r != '7')
{
r = multiply(r, m);
r = r + strlen(r) - k;
count++;
}
printf("%d\n", count);
}
return 0;
}
``````

...全文
122 点赞 收藏 9

9 条回复

C语言

3.2w+

24.0w+

C语言相关问题讨论