第一次作业

第一次作业


简单乘法(迭代)

实现代码如下

#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);
}

练习题

第6题

请添加图片描述

第8题在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值