Python中查找质因数

Python计算质数的多种方法 计算质数是数学和计算机科学中的一个经典问题,涉及多种算法和技术。本文介绍了计算质数的多种方法,包括基础方法、更高效的方法和Python中的内置函数和模块。选择合适的方法取决于具体的需求和性能要求。 阅读详情

如何在Python中进行素因式分解。

质因数分解的概述

在数学中,一个数的因数是指那些可以除以给定数并留下零余数的数字。

质数是只有两个因数的独特数字,一个和数字本身。这类数字的一些例子是3,7,11,13,等等。

素数因数化是指找到所有乘以原数的素数。我们可以考虑一个简单的例子:数字6。

这个数字的质因数分解产生了两个因子,即2和3。
在Python中寻找质因数的不同方法

我们可以用不同的方法找到指定数字的质因数。本文将演示下面列出的三种方法:

  • 创建一个自定义函数
  • 使用Sieve of Eratosthenes
  • 使用primefac 模块

让我们先在Python中创建一个自定义函数。

执行质因数分解的自定义函数

在数学中,最基本的质因数分解方法是重复除法。我们重复地用数字除以质数。我们可以在Python中使用嵌套循环来实现这一点。

第一个循环确定一个数字是否是素数。第二个循环将这个质数和给定的数字相除。

如果余数为零,我们就把这个质数追加到一个列表中。该函数返回最后的列表。请看下面的代码。

def p_factorization(n):
    i = 2
    lst = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            lst.append(i)
    if n > 1
python经典百题之分解质因数 因此,我们可以先判断2是否是n的质因数,如果是,则将其保存下来,并将n除以2,继续进行同样的操作,直到n为奇数,然后从3开始,依次判断所有的奇数是否是n的质因数。然而,在实际运行中,试除法的效率并不如分解质因数法,因为试除法需要进行大量的除法运算,而分解质因数法只需要进行少数的除法运算,因此试除法的效率较低。思路:从2到n-1依次判断n是否能够被整除,如果能够被整除,则说明存在一个质因数,将其保存下来,并将n除以该质因数,然后继续对n进行同样的操作。重复上述步骤,直到n变为1,最终得到所有的质因数。 阅读详情

相关推荐

头歌 python 练习五 循环结构

在宫廷举办的数学竞赛中,斐波那契曾提出过如下的“苹果问题”:一个人经过n道门进入苹果园,摘了许多苹果。相传韩信才智过人,从不直接清点自己军队的人数,只要让士兵先后以三人一排、五人一排、七人一排地变换队形,而他每次只掠一眼队伍的排尾(余下的人数)就知道总人数了。输入3个非负整数a,b,c ,表示每种队形排尾的人数(a<3,b<5,c<7),输出总人数的最小值(或报告无解)。银行信息.csv文件如下所示:每行显示银行的编号,名称,省份,城市和类别信息。给出一个长的DNA字符串s,和一个较短的DNA字符串t。

weixin_55703069的博客 3412

Python实现高效的质因数分解算法

设要分解的正整数为n,将其标记为当前的最小质因子p,然后从p开始,依次尝试将n除以2、3、5、7、11、13…具体实现中,可以使用一个while循环不断地除以当前的最小质因子p,直到无法整除为止,然后将p更新为下一个质数,继续进行除法操作,直到n被分解为1为止。这个算法的时间复杂度主要取决于分解出来的质因数个数,因为质因数没有重复,所以分解出的质因数个数最多为log2(n)个。在while循环中,我们不断地尝试将n除以p,如果可以整除,就记录下p,并将n更新为n//p,否则就将p更新为下一个质数。

BUG?不存在的! 1045

告别算力焦虑:手把手教你用华为CloudMatrix384超节点部署MoE大模型(附xDeepServe配置)

本文详细解析了如何在华为CloudMatrix384超节点上高效部署MoE大模型,通过xDeepServe框架配置和专家分配优化,实现2300 Tokens/s的推理吞吐。文章涵盖环境准备、性能调优、成本平衡及容灾设计,帮助开发者告别算力焦虑,提升AI推理效率。

weixin_30790841的博客 443

QGIS v3.28 高效加载OSM在线地图的三种实用方法

本文详细介绍了在QGIS v3.28中高效加载OSM在线地图的三种实用方法:通过XYZ Tiles直接连接、使用QuickMapServices插件以及配置WMS/WTMS服务。针对每种方法提供了具体操作步骤、常见问题解决方案和性能优化建议,帮助用户根据需求选择最适合的方案,提升GIS工作效率。

weixin_29233333的博客 435

告别混乱接线!用EPLAN 3D布局图,手把手教你搞定电气柜的3D建模与自动布线

本文详细介绍了如何使用EPLAN 3D布局图进行电气柜的3D建模与自动布线,帮助工程师告别混乱接线。从项目准备、基础结构建模到智能设备布局与逻辑定义,再到高级布线技术与问题排查,提供了一套完整的实战指南。通过EPLAN的3D功能,显著提升设计效率与系统可靠性。

weixin_30680385的博客 341

使用STM32F103C8T6控制舵机丝滑运转附代码

使用STM32F103C8T6控制舵机丝滑运转原理和案例,附代码。

m0_63566592的博客 4238

卡门涡街可视化实战:从网格加密策略到动画后处理技巧

本文详细介绍了利用ANSYS Fluent进行卡门涡街可视化模拟的全流程,包括网格加密策略、求解器设置、涡街捕捉及动画后处理技巧。通过计算流体力学(CFD)方法,帮助工程师和研究人员高效模拟圆柱绕流现象,优化工程设计。

weixin_29309785的博客 415

从Gotham到Foundry:一文读懂Palantir三大产品线(Gotham/Foundry/Apollo)的核心差异与适用场景

本文深度解析Palantir三大产品线Gotham、Foundry和Apollo的核心差异与适用场景。Gotham专为国防与情报设计,提供军事级安全分析;Foundry是企业数字化转型的通用平台,支持低代码开发;Apollo则是云原生基石,确保系统可靠运行。通过对比产品架构与典型应用,帮助技术决策者根据需求做出明智选择。

weixin_42524499的博客 843

英飞凌TC397芯片时钟树详解:从EB-tresos配置到PLL锁相环实战避坑

本文详细解析了英飞凌TC397芯片的时钟树架构,从EB-tresos配置到PLL锁相环的实战应用,帮助工程师避免常见配置陷阱。文章深入探讨了时钟源层、频率转换层和分配网络层的设计原理,提供了PLL配置的数学公式和EB-tresos关键容器的配置要点,并分享了调试技巧与性能优化实践,适用于MCU开发中的时钟管理需求。

weixin_42524226的博客 212

华为OD 面试手撕代码真题【判断链表是否有环】

华为OD 面试手撕代码真题【判断链表是否有环】

MISAYAONE的博客 7239

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

深度学习工具包 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")

上一篇: Python中匹配模糊的字符串
下一篇: Python获取主目录的方法
Python热爱者
博客等级 码龄7年 3056粉丝 1330原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值