扩展gcd以及同余方程ax=b(mod M)

一元线性同余方程简介 一元线性同余方程 阅读详情

关于扩展gcd其实没有必要搞懂,背下来就好了如果不会的自行学习

对于方程ax=b(mod M),我们可以将其化简成为ax+My=b,让后用扩展gcd求解

当b|r=gcd(a,M)时,方程有r个解,否则无解,对于有解的情况,每个解为用gcd求出的x乘上b/r+k*(M/r)

int extgcd(int a,int b,int& x,int& y){
	if(b){
		int r=extgcd(b,a%b,y,x);
		y-=x*(a/b); return r;
	} else { x=1; y=0; return a; }
}
int solve(int a,int b,int M){
	int x,y,r=extgcd(A,M,x,y);
	if(B%r) return -1; else x=(x+M)%M*b/r;
	// return x; 这个是返回通解
	return x%(M/r); //返回最小解
} 


Verilog实现SPI通信协议驱动设计 线性序列机实现SPI协议 阅读详情

相关推荐

3GPP协议解读_NTN系列(一)_38.811_非地面网络(NTN)的背景、应用场景和信道建模

非地面网络覆盖广,对物理攻击和自然灾害有一定的抵抗性。本文根据3GPP协议对NTN网络的背景、应用场景和信道模型进行了整理。

JCMLSY的博客 4940

求解ax===b(mod m)的特解和[0,m)的所有解

这里写代码片 ///用于计算ax==b(mod m)的一个特解,如果没有特解返回m本身 LL gcd_ex(LL a,LL b,LL &x,LL &y) { if(b==0) {x=1;y=0;return a;} LL d=gcd_ex(b,a%b,y,x); y=y-a/b*x; return d; } LL solve(LL a,LL b,LL m) {

布呗之路 2354

halcon与c#联合编程实现相机控制+图像平移缩放+日志记录+缺陷检测+路径规划

halcon与c#联合编程实现相机控制+图像平移缩放+日志记录+缺陷检测+路径规划 前言 本人近期在工作中遇到需要对某场景下利用海康相机进行图像缺陷检测与对应路径规划。通过对海康相机示例代码进行吸收与借鉴,最终实现了对海康相机的控制,并增加HSmartWindowControl控件,实现图像的实时显示与平移缩放功能;通过listview+toolstrip实现日志显示与类型(提示、警告、错误)分类;同时自行编制算法实现对缺陷的识别以及缺陷外扩矩形范围内的路径规划。 1.日志记录 代码如下(示例):

weixin_37864926的博客 2723

扩展欧几里得应用2(数论)

题目描述 【题意】 已知a,b,m,求x的最小正整数解,使得ax=b(mod m) 【输入格式】 一行三个整数 a,b,m。 1 ≤ a,b,m ≤ 10^9  【输出格式】 一行一个整数x,无解输出"no solution!" 【样例输入】 2 5 7 【样例输出】 6 解释: 这题通俗讲就是 ax mod m=b mod m 那么 b 是个常数,所以直接 b=b%m,不影响结果 ax...

短发 355

用Python实现四叉树(quad tree)

import numpy as np #正方形类 class square: #lx、ly为左上角坐标(x对应行号,y对应列号),rx、ry为右下角坐标 def __init__(self,lx,ly,rx,ry): self.lx=lx self.ly=ly self.rx=rx self.ry=ry #检查该矩阵中是否满足条件 #参数:原矩阵,阈值 #返回值:布尔类型 def check(s

weixin_44164489的博客 5871

从想法到零件:手把手拆解一个汽车功能如何从PRD写到SSTS和CTS

本文详细拆解了汽车电子需求从市场文档(MRD)到零部件技术规范(CTS)的完整流程,以雨天自动关窗功能为例,展示了PRD、SSTS和CTS的编写要点与交互设计。文章重点解析了系统分解的艺术和零部件落地的精确参数要求,为汽车电子工程师提供了从概念到实现的全流程实践指南。

weixin_30300225的博客 484

扩展欧几里得算法

给定整数a,b,m,求解同余方程ax = b (mod m)x * b / gcd(a,m)即为原方程的特解。当gcd(a,m) | b 有解。即 ax + my = b;

aiwangyi6的博客 106

UNet改进(23):如何用SLCAM模块提升UNet的分割性能

本文提出一种改进的UNet架构,通过引入轻量化注意力模块(SLCAM)增强医学图像分割性能。SLCAM整合了通道和空间双重注意力机制:通道注意力采用全局池化和共享MLP学习通道权重,空间注意力通过7×7卷积捕捉上下文信息。网络在传统UNet基础上,在每个下采样和上采样块后加入SLCAM模块,并保持跳跃连接结构。实验表明,该方法能自适应聚焦重要特征,在不显著增加计算负担的情况下提升分割精度,特别适用于医学图像等需精确边界的场景。未来可探索三维注意力、动态参数调整等改进方向。

2501_91516851的博客 446

编程实现计算同余式ax≡b(mod m)的解

def gcd(a,b): if a>b: a,b=b,a if b%a==0: return a else: return gcd(a,b%a) a=int(input("a=")) b=int(input("b=")) m=int(input("m=")) i=2 j=1 x1=gcd(a,m) x2=a/x1 if(b%x1==0): while(x2%(m/x1)!=1): x2=a/x1...

Draina的博客 1401

2、探秘储备池计算:原理、应用与前沿趋势

储备池计算(Reservoir Computing)作为一种新兴的计算方法,起源于计算神经科学和机器学习领域,现已广泛应用于非线性动力系统理论、物理学、材料科学、生物学和机器人学等多个领域。其核心优势在于概念简洁性,通过利用高维动态系统的非线性响应,将学习过程集中在读出层,避免了传统循环神经网络(RNN)训练的复杂性。储备池计算的发展方向主要包括拓展到非线性动态系统和利用物理动态系统作为计算资源(PRC),后者有望突破冯·诺依曼瓶颈,实现边缘计算。理论方面,储备池计算与人类大脑的信息处理方式密切相关,并推动

ggg99的专栏 750

【Claude Code 源码解析教程】总体大纲

本教程旨在深入解析 Anthropic Claude Code 项目的源码架构和实现细节。Claude Code 是一个基于 TypeScript + Bun 构建的 AI 编程助手 CLI 工具,代号 "Tengu",具有复杂的多模块架构和丰富的功能特性。本教程基于Claude Code 的源码分析来生成,将帮助您全面掌握 Claude Code 的源码架构和实现细节,为开发类似 AI 编程助手工具奠定坚实基础。

rengang66的博客 394

poj 2115 C Looooops(解线性同余方程)

C Looooops Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 19017   Accepted: 5003 Description A Compiler Mystery: We are given a C-language style for loop of t

llin-黎辰 621

【图像分类】卷积神经网络之VGGNet网络模型实现花卉图像识别(附代码和数据集,PyTorch框架)

卷积神经网络之VGGNet网络模型实现花卉图像识别(附代码和数据集,PyTorch框架)

学无止境、积少成多、厚积薄发 2434

扩展欧几里得算法(详细推导+代码实现+应用)

1.扩展欧几里得算法 贝祖定理:若a,b是整数,且gcd(a,b)=d,那么对于任意的整数x,y,ax+by=m中的m一定是d的倍数。(特别地,如果a、b是整数,那么一定存在整数x、y使得ax+by=gcd(a,b)。) 那么贝祖定理的一个直接应用就是:如果ax+by=1有解,那么gcd(a,b)=1(将原公式两边同时除以gcd(a,b))。 扩展欧几里得算法用来解决这样一个问题:给定两个非零的整...

胡小涛的博客 1万+

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【模板题】扩展欧几里得算法与线性同余方程

【题目描述】 给定nnn对正整数ai,bia_i,b_iai​,bi​,对于每对数,求出一组xi,yix_i,y_ixi​,yi​,使其满足ai×xi+bi×yi=gcd(ai,bi)a_i\times x_i+b_i\times y_i=gcd(a_i,b_i)ai​×xi​+bi​×yi​=gcd(ai​,bi​)。 【输入格式】 第一行包含整数nnn。 接下来nnn行,每行包含两个整数ai,bia_i,b_iai​,bi​。 【输出格式】 输出共nnn行,对于每组ai,bia_i,b_iai​,bi​

一只快乐的小蒟蒻~ 393

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

@TODO

1

qq_66485519的博客 807

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

数论算法精讲:快速幂、扩展欧几里得与欧拉降幂原理与应用

在算法竞赛与密码学实践中,模运算与数论算法是处理大数计算的核心基础。其核心原理在于利用模运算的代数性质,将复杂的整数运算约束在有限域内,从而在保证结果正确性的前提下,大幅提升计算效率并避免数值溢出。这一技术价值在于为RSA加密、离散对数问题等现代密码学基石提供了可行的计算工具,同时也是解决动态规划中状态转移优化等高性能计算场景的关键。具体到应用场景,当需要高效计算a的b次方对m取模时,快速幂算法通过二进制分解将复杂度降至对数级;而在求解模线性方程或计算模逆元时,扩展欧几里得算法则不可或缺;当指数b本身也极大

weixin_34067102的博客 531

第四章 数学知识 扩展欧几里得算法

1、扩展欧几里得算法 已知整数a、b,扩展欧几里得算法可以在求得a、b的最大公约数的同时,能找到整数x、y(其中一个很可能是负数),使它们满足等式ax+by=gcd(a,b)ax+by=gcd(a,b)ax+by=gcd(a,b) ps:这个gcd(a,b)是a和b能凑出来的最小的正整数 int exgcd(int a, int b, int &x, int &y) { if(b == 0) { x = 1,y = 0; return a; }

刘胖仔学后端 343

数论-同余模定理和欧几里德算法

扩展的欧几里德算法不仅可以用来求解gcd(a, b),还可以用来求解一对整数(x, y),使得 xa + yb = gcd(a, b)。显然,当gcd(a, b) = 1时,有xa + yb = 1,则在模b情况下x是a的乘法逆元,在模a情况下y是b的乘法逆元。 推导过程: 1、当b = 0时,gcd(a, b) = a, 则 x = 1,y = 0满足条件。 2、当a、b xa + y

风华绝代 1659

数论学习笔记:同余基础

目前我学习了一些很基础的数论算法和思想,其中主要关于同余。先来看这样一个方程: ax+by=cax + by = cax+by=c (其中 a,b,ca,b,ca,b,c 是已知常数)也就是说,方程的未知数的数量大于方程数,这就叫不定方程。上面这个就是典型的二元一次不定方程。我们可以设 d=gcd(a,b)d = gcd(a, b)d=gcd(a,b),则 d∣a, d∣bd\mid a,\ d\mid bd∣a, d∣b,则 d∣ax+byd\mid ax + byd∣ax+by,所以 d∣cd\mid

Vicco_Li的博客 368

ZOJ 3609 Modular Inverse

ZOJ 3609 1 #include <cstdio> 2 #include <cmath> 3 using namespace std; 4 int ex_gcd(int a,int b,int &x,int &y)//solve x,y in a*x+b*y=ex_gcd(a,b,x,y)=gcd(a,b); 5 { 6...

weixin_30917213的博客 62

讲解

扩展欧几里得算法 用于求解方程 ax+by=gcd(a,b) 的解 当 b=0时 ax+by=a 故而 x=1,y=0 当 b≠0 时 gcd(a,b)=gcd(b,a%b) 对于gcd(b,a%b) bx′+(a%b)y′=gcd(b,a%b) bx′+(a−⌊a/b⌋∗b)y′=gcd(b,a%b) ay′+b(x′−⌊a/b⌋∗y′)=gcd(b,a%b)=gcd(a,b)

H_L__的博客 496

数学知识——同余

线性同余方程 对于一组a,b,ma,b,ma,b,m,我们想要求出一个xxx,使得ax≡b(mod m)ax≡b(mod\ m)ax≡b(mod m)。 ax≡b(mod m)ax≡b(mod\ m)ax≡b(mod m) ax=km+bax=km+bax=km+b ax−km=bax-km=bax−km=b 令k′=−kk^{'}=-kk′=−k ax+k′m=bax+k^{'}m=bax+k′m=b 如果bbb不是(a,m)(a,m)(a,m)的倍数,那么一定无解,因为ax+k′max+k^{'}max

m0_70897036的博客 1192

poj 2142 解线性同余方程 扩展gcd变形

题目传送门 1.先贴一个比较暴力的    547ms #include&lt;iostream&gt; #include&lt;cstdio&gt; #include&lt;cmath&gt; #include&lt;algorithm&gt; using namespace std; typedef long long LL; const LL INF=0x3f3f3f3f; void e...

老铁,干了这碗algorithms的博客 247
上一篇: Jzoj1158荒岛野人
下一篇: Jzoj1164求和
扩展的灰
博客等级 码龄12年 60粉丝 342原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值