第一次作业
文章目录
简单乘法(迭代)
实现代码如下
:
#include<iostream>
using namespace std;
int multiplication(int a, int b) {
int ans = 0;
while (b != 0) {
if (b & 1)ans += a;
a = a << 1;
b = b >> 1;
}
return ans;
}
int main() {
int a,b;
cout << "请输入所乘之数:";
cin >>a>>b;
cout << a << "*" << b << "=" << multiplication(a, b);
}
除法算法的完整证明
存在性
构造集合:
S={a-bk:b∈Z且a-bk≥0}.
∵S≠∅,
∴由良序原则,存在最小元r∈S,且r=a-qb.
∴a=qb+r,r≥0.
接下来证明r<b:
若r>b,则存在r‘=a-(q+1)b,r不再是最小元,与假设相左,故r<b.
唯一性
迭代版本的gcd算法和egcd算法
代码如下:
#include<iostream>
using namespace std;
int gcd(int a, int b) {
while (b != 0) {
int temp = a;
a = b;
b = temp % b;
}
return a;
}
int Count(int n) {
int count = 0;
for (int i = 1; i < n; i++) {
if (gcd(n, i) == 1) {
count++;
}
}
return count;
}
int binary_egcd(int a, int b) {
int k = 0;
while (((a | b) & 1) == 0) {
a = a >> 1;
b = b >> 1;
k = k + 1 ;
}
int r0 = a, r1 = b;
int s0 = 1, s1 = 0, t0 = 0, t1 = 1;
while (r1 != 0) {
while ((r0 & 1) == 0) {
r0 = r0 >> 1;
if (((s0 | t0) & 1) == 0) {
s0 = s0 >> 1;
t0 = t0 >> 1;
}
else {
s0 = (s0 + b) >> 1;
t0 = (t0 - a) >> 1;
}
}
while ((r1 & 1) == 0) {
r1 = r1 >> 1;
if (((s1 | t1) & 1) == 0) {
s1 = s1 >> 1;
t1 = t1 >> 1;
}
else {
s1 = (s1 + b) >> 1;
t1 = (t1 - a) >> 1;
}
}
if (r1 < r0) {
std::swap(r0, r1);
std::swap(s0, s1);
std::swap(t0, t1);
}
r1 = r1 - r0;
s1 = s1 - s0;
t1 = t1 - t0;
}
return (r0 << k), s0, t0;
}
int main() {
int n;
cout << "请输入所求之数:";
cin >>n;
Count(n);
}