Binary mod and divide

Posted zdragon

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Binary mod and divide相关的知识,希望对你有一定的参考价值。

               4030: Binary mod and divide 

时间限制(普通/Java):1000MS/3000MS     内存限制:65536KByte

描述

Most people know that the binary operations. Do you know the binary mod and divide?

Now give the Binary number N and a integer number M ,Can you tell me the answer of N%(2^M) and N/(2^M)?

输入

Input contains multiple test cases.

The first line of each test case contains an binary number N no more than 128 bits and an integer M (1 <= M <= 64).

when N=0&&M=0 ,test is over.

输出

output the answer the N%(2^M) and N/(2^M).

样例输入

111 2

1111 2

0 0

样例输出

3

3 2
4 1

这是一个有意思的题目:

题目大意是:给一个不超过128为的二进制数N,和一个整数M,求N%(2^M)和N/(2^M).

把2^M次转化成二进制,就是1后面M个0,那么就相当于N的最小位开始数M个数就是余数,剩下的就是倍数了。

接下来就是计算了,2^128次longlong存不下,所以用数组存了。

代码:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <iostream>
 4 using namespace std;
 5 char a[150];
 6 void add(int l,int r,int b[])
 7 {
 8     for(int i=l;i<r;i++)
 9     {
10         for(int j=0;j<40;j++)
11             b[j]*=2;
12         b[0]+=a[i]-0;
13         for(int j=0;j<40;j++)
14         {
15             if(b[j]>=10)
16             {
17                 b[j+1]+=b[j]/10;
18                 b[j]%=10;
19             }
20         }
21     }
22 }
23 int main()
24 {
25     int m,i,l;
26     int b[45],c[45];
27     while(scanf("%s%d",a,&m))
28     {
29         if(!m&&a[0]==0) break;
30         memset(b,0,sizeof(b));
31         memset(c,0,sizeof(c));
32         l=strlen(a);
33         add(0,l-m,b);
34         add(max(0,l-m),l,c);
35         printf("mod=");
36         for(i=39;i>=0;i--)
37             if(c[i]) break;
38         if(i==-1) printf("0");
39         for(;i>=0;i--)
40             printf("%d",c[i]);
41         printf(", divide=");
42         for(i=39;i>=0;i--)
43             if(b[i]) break;
44         if(i==-1) printf("0");
45         for(;i>=0;i--)
46             printf("%d",b[i]);
47         putchar(10);
48     }
49 }

 

以上是关于Binary mod and divide的主要内容,如果未能解决你的问题,请参考以下文章

algorithm@ Divide two integers without using multiplication, division and mod operator. (Bit Operati

Codeforces 551D - GukiZ and Binary Operations 矩阵快速幂

LintCode 7.Serialize and Deserialize Binary Tree(含测试代码)

E. Binary Numbers AND Sum

Binary Tree - Divide Conquer & Traverse

解决go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘(代码片段