├── .gitignore ├── test ├── README.md ├── LICENSE └── pyecm.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/** 2 | *.pyc 3 | -------------------------------------------------------------------------------- /test: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import os 4 | import sys 5 | 6 | if len(sys.argv) != 2: 7 | print('Usage: ./test PYECM_PATH') 8 | sys.exit(-1) 9 | parent_dir = os.path.realpath(os.path.join(sys.argv[1], os.pardir)) 10 | sys.path.insert(0, parent_dir) 11 | 12 | from pyecm import * 13 | 14 | for n in range(1, 1001): 15 | prod = 1 16 | for factor in factors(n, False, False, 7.97308847044, 1.0): 17 | prod *= factor 18 | if prod != n: 19 | print('Failed to factor %d.' % n, file=sys.stderr) 20 | sys.exit(1) 21 | print('All tests passed.') 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pyecm 2 | Pyecm factors large integers (up to 50 digits) using the Elliptic Curve Method 3 | (ECM), a fast factoring algorithm. 4 | 5 | Pyecm was a high-school project for myself (Martin Kelly) and my friend, Eric 6 | Larson. Eric did more of the math and I did most of the code. Although the code 7 | is not very clean by my standards today, it works and is quite fast. It was also 8 | a nice illustration of how Python can be used for performance-critical code, if 9 | the bottlenecks are clearly identified and implemented in C. In our case, we do 10 | this via the wonderful gmpy. 11 | 12 | # How to run pyecm 13 | 14 | ## All platforms 15 | - First, make sure python (>= 2.3) is installed and working. You can always get 16 | the latest release from http://python.org 17 | - For speed increases, you may optionally install gmpy and/or psyco. Both are 18 | highly recommended, especially gmpy, as they result in massive speed increases. 19 | 20 | ## Unix, Linux, Mac 21 | - You can either use *python pyecm.py* to run it or change the filename to pyecm 22 | and execute it as a script. 23 | 24 | ## Windows 25 | - Just run pyecm.py as you would any other python program. 26 | 27 | # Related projects 28 | - Old home for pyecm on Sourceforge (https://sourceforge.net/projects/pyecm) 29 | - gmpy (https://github.com/aleaxit/gmpy) 30 | - psyco (http://psyco.sourceforge.net/) 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Library General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License 307 | along with this program; if not, write to the Free Software 308 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 309 | 310 | 311 | Also add information on how to contact you by electronic and paper mail. 312 | 313 | If the program is interactive, make it output a short notice like this 314 | when it starts in an interactive mode: 315 | 316 | Gnomovision version 69, Copyright (C) year name of author 317 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 318 | This is free software, and you are welcome to redistribute it 319 | under certain conditions; type `show c' for details. 320 | 321 | The hypothetical commands `show w' and `show c' should show the appropriate 322 | parts of the General Public License. Of course, the commands you use may 323 | be called something other than `show w' and `show c'; they could even be 324 | mouse-clicks or menu items--whatever suits your program. 325 | 326 | You should also get your employer (if you work as a programmer) or your 327 | school, if any, to sign a "copyright disclaimer" for the program, if 328 | necessary. Here is a sample; alter the names: 329 | 330 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 331 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 332 | 333 | , 1 April 1989 334 | Ty Coon, President of Vice 335 | 336 | This General Public License does not permit incorporating your program into 337 | proprietary programs. If your program is a subroutine library, you may 338 | consider it more useful to permit linking proprietary applications with the 339 | library. If this is what you want to do, use the GNU Library General 340 | Public License instead of this License. 341 | -------------------------------------------------------------------------------- /pyecm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ''' 4 | You should install psyco and gmpy if you want maximal speed. 5 | 6 | Filename: pyecm 7 | Authors: Eric Larson , Martin Kelly , Matt Ford 8 | License: GNU GPL (see for more information. 9 | Description: Factors a number using the Elliptic Curve Method, a fast algorithm for numbers < 50 digits. 10 | 11 | We are using curves in Suyama's parametrization, but points are in affine coordinates, and the curve is in Wierstrass form. 12 | The idea is to do many curves in parallel to take advantage of batch inversion algorithms. This gives asymptotically 7 modular multiplications per bit. 13 | 14 | WARNING: pyecm is NOT a general-purpose number theory or elliptic curve library. Many of the functions have confusing calling syntax, and some will rather unforgivingly crash or return bad output if the input is not formatted exactly correctly. That said, there are a couple of functions that you CAN safely import into another program. These are: factors, isprime. However, be sure to read the documentation for each function that you use. 15 | ''' 16 | 17 | import math 18 | import sys 19 | import random 20 | 21 | try: 22 | import psyco 23 | psyco.full() 24 | PSYCO_EXISTS = True 25 | except ImportError: 26 | PSYCO_EXISTS = False 27 | 28 | try: # Try to use gmpy 29 | from gmpy2 import isqrt as sqrt 30 | from gmpy2 import iroot as root 31 | from gmpy2 import gcd, invert, mpz, next_prime 32 | import gmpy2 33 | GMPY_EXISTS = True 34 | except ImportError: 35 | try: 36 | from gmpy import gcd, invert, mpz, next_prime, sqrt, root 37 | GMPY_EXISTS = True 38 | except ImportError: 39 | GMPY_EXISTS = False 40 | 41 | if not GMPY_EXISTS: 42 | PRIMES = (5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 167) 43 | GMPY_EXISTS = False 44 | 45 | def gcd(a, b): 46 | '''Computes the Greatest Common Divisor of a and b using the standard quadratic time improvement to the Euclidean Algorithm. 47 | 48 | Returns the GCD of a and b.''' 49 | 50 | if b == 0: 51 | return a 52 | elif a == 0: 53 | return b 54 | 55 | count = 0 56 | 57 | if a < 0: 58 | a = -a 59 | if b < 0: 60 | b = -b 61 | 62 | while not ((a & 1) | (b & 1)): 63 | count += 1 64 | a >>= 1 65 | b >>= 1 66 | 67 | while not a & 1: 68 | a >>= 1 69 | 70 | while not b & 1: 71 | b >>= 1 72 | 73 | if b > a: 74 | b,a = a,b 75 | 76 | while b != 0 and a != b: 77 | a -= b 78 | while not (a & 1): 79 | a >>= 1 80 | 81 | if b > a: 82 | b, a = a, b 83 | 84 | return a << count 85 | 86 | def invert(a, b): 87 | '''Computes the inverse of a modulo b. b must be odd. 88 | 89 | Returns the inverse of a (mod b).''' 90 | if a == 0 or b == 0: 91 | return 0 92 | 93 | truth = False 94 | if a < 0: 95 | truth = True 96 | a = -a 97 | 98 | b_orig = b 99 | alpha = 1 100 | beta = 0 101 | 102 | while not a & 1: 103 | if alpha & 1: 104 | alpha += b_orig 105 | alpha >>= 1 106 | a >>= 1 107 | 108 | if b > a: 109 | a, b = b, a 110 | alpha, beta = beta, alpha 111 | 112 | while b != 0 and a != b: 113 | a -= b 114 | alpha -= beta 115 | 116 | while not a & 1: 117 | if alpha & 1: 118 | alpha += b_orig 119 | alpha >>= 1 120 | a >>= 1 121 | 122 | if b > a: 123 | a,b = b,a 124 | alpha, beta = beta, alpha 125 | 126 | if a == b: 127 | a -= b 128 | alpha -= beta 129 | a, b = b, a 130 | alpha, beta = beta, alpha 131 | 132 | if a != 1: 133 | return 0 134 | 135 | if truth: 136 | alpha = b_orig - alpha 137 | 138 | return alpha 139 | 140 | def next_prime(n): 141 | '''Finds the next prime after n. 142 | 143 | Returns the next prime after n.''' 144 | n += 1 145 | if n <= 167: 146 | if n <= 23: 147 | if n <= 3: 148 | return 3 - (n <= 2) 149 | n += (n & 1) ^ 1 150 | return n + (((4 - (n % 3)) >> 1) & 2) 151 | 152 | n += (n & 1) ^ 1 153 | inc = n % 3 154 | n += ((4 - inc) >> 1) & 2 155 | inc = 6 - ((inc + ((2 - inc) & 2)) << 1) 156 | 157 | while 0 in (n % 5, n % 7, n % 11): 158 | n += inc 159 | inc = 6 - inc 160 | return n 161 | 162 | n += (n & 1) ^ 1 163 | inc = n % 3 164 | n += ((4 - inc) >> 1) & 2 165 | inc = 6 - ((inc + ((2 - inc) & 2)) << 1) 166 | should_break = False 167 | 168 | while 1: 169 | for prime in PRIMES: 170 | if not n % prime: 171 | should_break = True 172 | break 173 | 174 | if should_break: 175 | should_break = False 176 | n += inc 177 | inc = 6 - inc 178 | continue 179 | 180 | p = 1 181 | for i in range(int(math.log(n) / LOG_2), 0, -1): 182 | p <<= (n >> i) & 1 183 | p = (p * p) % n 184 | 185 | if p == 1: 186 | return n 187 | 188 | n += inc 189 | inc = 6 - inc 190 | 191 | def mpz(n): 192 | '''A dummy function to ensure compatibility with those that do not have gmpy. 193 | 194 | Returns n.''' 195 | return n 196 | 197 | def root(n, k): 198 | '''Finds the floor of the kth root of n. This is a duplicate of gmpy's root function. 199 | 200 | Returns a tuple. The first item is the floor of the kth root of n. The second is 1 if the root is exact (as in, sqrt(16)) and 0 if it is not.''' 201 | low = 0 202 | high = n + 1 203 | while high > low + 1: 204 | mid = (low + high) >> 1 205 | mr = mid**k 206 | if mr == n: 207 | return (mid, 1) 208 | if mr < n: 209 | low = mid 210 | if mr > n: 211 | high = mid 212 | return (low, 0) 213 | 214 | def sqrt(n): 215 | return root(n, 2)[0] 216 | 217 | # We're done importing. Now for some constants. 218 | if GMPY_EXISTS: 219 | INV_C = 1.4 220 | else: 221 | if PSYCO_EXISTS: 222 | INV_C = 7.3 223 | else: 224 | INV_C = 13.0 225 | LOG_2 = math.log(2) 226 | LOG_4 = math.log(4) 227 | LOG_3_MINUS_LOG_LOG_2 = math.log(3) - math.log(LOG_2) 228 | LOG_4_OVER_9 = LOG_4 / 9 229 | _3_OVER_LOG_2 = 3 / LOG_2 230 | _5_LOG_10 = 5 * math.log(10) 231 | _7_OVER_LOG_2 = 7 / LOG_2 232 | BIG = 2.0**512 233 | BILLION = 10**9 # Something big that fits into an int. 234 | MULT = math.log(3) / LOG_2 235 | ONE = mpz(1) 236 | SMALL = 2.0**(-30) 237 | SMALLEST_COUNTEREXAMPLE_FASTPRIME = 2047 238 | T = (type(mpz(1)), type(1), type(1)) 239 | DUMMY = 'dummy' # Dummy value throughout the program 240 | VERSION = '2.0.5 (Python 3)' 241 | _12_LOG_2_OVER_49 = 12 * math.log(2) / 49 242 | RECORD = 1162795072109807846655696105569042240239 243 | 244 | class ts: 245 | '''Does basic manipulations with Taylor Series (centered at 0). An example call to ts: 246 | a = ts(7, 23, [1<<23, 2<<23, 3<<23]) -- now, a represents 1 + 2x + 3x^2. Here, computations will be done to degree 7, with accuracy 2^(-23). Input coefficients must be integers.''' 247 | 248 | def __init__(self, degree, acc, p): 249 | self.acc = acc 250 | self.coefficients = p[:degree + 1] 251 | while len(self.coefficients) <= degree: 252 | self.coefficients.append(0) 253 | 254 | def add(self, a, b): 255 | '''Adds a and b''' 256 | b_ = b.coefficients[:] 257 | a_ = a.coefficients[:] 258 | self.coefficients = [] 259 | 260 | while len(b_) > len(a_): 261 | a_.append(0) 262 | while len(b_) < len(a_): 263 | b_.append(0) 264 | 265 | for i in range(len(a_)): 266 | self.coefficients.append(a_[i] + b_[i]) 267 | 268 | self.acc = a.acc 269 | 270 | def ev(self, x): 271 | '''Returns a(x)''' 272 | answer = 0 273 | for i in range(len(self.coefficients) - 1, -1, -1): 274 | answer *= x 275 | answer += self.coefficients[i] 276 | return answer 277 | 278 | def evh(self): 279 | '''Returns a(1/2)''' 280 | answer = 0 281 | for i in range(len(self.coefficients) - 1, -1, -1): 282 | answer >>= 1 283 | answer += self.coefficients[i] 284 | return answer 285 | 286 | def evmh(self): 287 | '''Returns a(-1/2)''' 288 | answer = 0 289 | for i in range(len(self.coefficients) - 1, -1, -1): 290 | answer = - answer >> 1 291 | answer += self.coefficients[i] 292 | return answer 293 | 294 | def int(self): 295 | '''Replaces a by an integral of a''' 296 | self.coefficients = [0] + self.coefficients 297 | for i in range(1, len(self.coefficients)): 298 | self.coefficients[i] = self.coefficients[i] // i 299 | 300 | def lindiv(self, a): 301 | '''a.lindiv(k) -- sets a/(x-k/2) for integer k''' 302 | for i in range(len(self.coefficients) - 1): 303 | self.coefficients[i] <<= 1 304 | self.coefficients[i] = self.coefficients[i] // a 305 | self.coefficients[i + 1] -= self.coefficients[i] 306 | self.coefficients[-1] <<= 1 307 | self.coefficients[-1] = self.coefficients[-1] // a 308 | 309 | def neg(self): 310 | '''Sets a to -a''' 311 | for i in range(len(self.coefficients)): 312 | self.coefficients[i] = - self.coefficients[i] 313 | 314 | def set(self, a): 315 | '''a.set(b) sets a to b''' 316 | self.coefficients = a.coefficients[:] 317 | self.acc = a.acc 318 | 319 | def simp(self): 320 | '''Turns a into a type of Taylor series that can be fed into ev, but cannot be computed with further.''' 321 | for i in range(len(self.coefficients)): 322 | shift = max(0, int(math.log(abs(self.coefficients[i]) + 1) / LOG_2) - 1000) 323 | self.coefficients[i] = float(self.coefficients[i] >> shift) 324 | shift = self.acc - shift 325 | for _ in range(shift >> 9): 326 | self.coefficients[i] /= BIG 327 | self.coefficients[i] /= 2.0**(shift & 511) 328 | if (abs(self.coefficients[i] / self.coefficients[0]) <= SMALL): 329 | self.coefficients = self.coefficients[:i] 330 | break 331 | 332 | # Functions are declared in alphabetical order except when dependencies force them to be at the end. 333 | 334 | def add(p1, p2, n): 335 | '''Adds first argument to second (second argument is not preserved). The arguments are points on an elliptic curve. The first argument may be a tuple instead of a list. The addition is thus done pointwise. This function has bizzare input/output because there are fast algorithms for inverting a bunch of numbers at once. 336 | 337 | Returns a list of the addition results.''' 338 | inv = list(range(len(p1))) 339 | 340 | for i in range(len(p1)): 341 | inv[i] = p1[i][0] - p2[i][0] 342 | 343 | inv = parallel_invert(inv, n) 344 | 345 | if not isinstance(inv, list): 346 | return inv 347 | 348 | for i in range(len(p1)): 349 | m = ((p1[i][1] - p2[i][1]) * inv[i]) % n 350 | p2[i][0] = (m * m - p1[i][0] - p2[i][0]) % n 351 | p2[i][1] = (m * (p1[i][0] - p2[i][0]) - p1[i][1]) % n 352 | 353 | return p2 354 | 355 | def add_sub_x_only(p1, p2, n): 356 | '''Given a pair of lists of points p1 and p2, computes the x-coordinates of 357 | p1[i] + p2[i] and p1[i] - p2[i] for each i. 358 | 359 | Returns two lists, the first being the sums and the second the differences.''' 360 | sums = list(range(len(p1))) 361 | difs = list(range(len(p1))) 362 | 363 | for i in range(len(p1)): 364 | sums[i] = p2[i][0] - p1[i][0] 365 | 366 | sums = parallel_invert(sums, n) 367 | 368 | if not isinstance(sums, list): 369 | return (sums, None) 370 | 371 | for i in range(len(p1)): 372 | ms = ((p2[i][1] - p1[i][1]) * sums[i]) % n 373 | md = ((p2[i][1] + p1[i][1]) * sums[i]) % n 374 | sums[i] = (ms * ms - p1[i][0] - p2[i][0]) % n 375 | difs[i] = (md * md - p1[i][0] - p2[i][0]) % n 376 | 377 | sums = tuple(sums) 378 | difs = tuple(difs) 379 | 380 | return (sums, difs) 381 | 382 | def atdn(a, d, n): 383 | '''Calculates a to the dth power modulo n. 384 | 385 | Returns the calculation's result.''' 386 | x = 1 387 | pos = int(math.log(d) / LOG_2) 388 | 389 | while pos >= 0: 390 | x = (x * x) % n 391 | if (d >> pos) & 1: 392 | x *= a 393 | pos -= 1 394 | 395 | return x % n 396 | 397 | def copy(p): 398 | '''Copies a list using only deep copies. 399 | 400 | Returns a copy of p.''' 401 | answer = [] 402 | for i in p: 403 | answer.append(i[:]) 404 | 405 | return answer 406 | 407 | def could_be_prime(n): 408 | '''Performs some trials to compute whether n could be prime. Run time is O(N^3 / (log N)^2) for N bits. 409 | 410 | Returns whether it is possible for n to be prime (True or False). 411 | ''' 412 | if n < 2: 413 | return False 414 | if n == 2: 415 | return True 416 | if not int(n) & 1: 417 | return False 418 | 419 | product = ONE 420 | log_n = int(math.log(n)) + 1 421 | bound = int(math.log(n) / (LOG_2 * math.log(math.log(n))**2)) + 1 422 | if bound * log_n >= n: 423 | bound = 1 424 | log_n = int(sqrt(n)) 425 | prime_bound = 0 426 | prime = 3 427 | 428 | for _ in range(bound): 429 | p = [] 430 | prime_bound += log_n 431 | while prime <= prime_bound: 432 | p.append(prime) 433 | prime = next_prime(prime) 434 | if p != []: 435 | p = prod(p) 436 | product = (product * p) % n 437 | 438 | return gcd(n, product) == 1 439 | 440 | def double(p, n): 441 | '''Doubles each point in the input list. Much like the add function, we take advantage of fast inversion. 442 | 443 | Returns the doubled list.''' 444 | inv = list(range(len(p))) 445 | for i in range(len(p)): 446 | inv[i] = p[i][1] << 1 447 | 448 | inv = parallel_invert(inv, n) 449 | 450 | if not isinstance(inv, list): 451 | return inv 452 | 453 | for i in range(len(p)): 454 | x = p[i][0] 455 | m = (x * x) % n 456 | m = ((m + m + m + p[i][2]) * inv[i]) % n 457 | p[i][0] = (m * m - x - x) % n 458 | p[i][1] = (m * (x - p[i][0]) - p[i][1]) % n 459 | return p 460 | 461 | def fastprime(n): 462 | '''Tests for primality of n using an algorithm that is very fast, O(N**3 / log(N)) (assuming quadratic multiplication) where n has N digits, but ocasionally inaccurate for n >= 2047. 463 | 464 | Returns the primality of n (True or False).''' 465 | if not could_be_prime(n): 466 | return False 467 | if n == 2: 468 | return True 469 | 470 | j = 1 471 | d = n >> 1 472 | 473 | while not d & 1: 474 | d >>= 1 475 | j += 1 476 | 477 | p = 1 478 | pos = int(math.log(d) / LOG_2) 479 | 480 | while pos >= 0: 481 | p = (p * p) % n 482 | p <<= (d >> pos) & 1 483 | pos -= 1 484 | 485 | if p in (n - 1, n + 1): 486 | return True 487 | 488 | for _ in range(j): 489 | p = (p * p) % n 490 | 491 | if p == 1: 492 | return False 493 | elif p == n - 1: 494 | return True 495 | 496 | return False 497 | 498 | def greatest_n(phi_max): 499 | '''Finds the greatest n such that phi(n) < phi_max. 500 | 501 | Returns the greatest n such that phi(n) < phi_max.''' 502 | phi_product = 1 503 | product = 1 504 | prime = 1 505 | while phi_product <= phi_max: 506 | prime = next_prime(prime) 507 | phi_product *= prime - 1 508 | product *= prime 509 | 510 | n_max = (phi_max * product) // phi_product 511 | phi_values = list(range(n_max)) 512 | 513 | prime = 2 514 | while prime <= n_max: 515 | for i in range(0, n_max, prime): 516 | phi_values[i] -= phi_values[i] // prime 517 | 518 | prime = next_prime(prime) 519 | 520 | for i in range(n_max - 1, 0, -1): 521 | if phi_values[i] <= phi_max: 522 | return i 523 | 524 | def inv_const(n): 525 | '''Finds a constant relating the complexity of multiplication to that of modular inversion. 526 | 527 | Returns the constant for a given n.''' 528 | return int(INV_C * math.log(n)**0.42) 529 | 530 | def naf(d): 531 | '''Finds a number's non-adjacent form, reverses the bits, replaces the 532 | -1's with 3's, and interprets the result base 4. 533 | 534 | Returns the result interpreted as if in base 4.''' 535 | g = 0 536 | while d: 537 | g <<= 2 538 | g ^= ((d & 2) & (d << 1)) ^ (d & 1) 539 | d += (d & 2) >> 1 540 | d >>= 1 541 | return g 542 | 543 | def parallel_invert(l, n): 544 | '''Inverts all elements of a list modulo some number, using 3(n-1) modular multiplications and one inversion. 545 | 546 | Returns the list with all elements inverted modulo 3(n-1).''' 547 | l_ = l[:] 548 | for i in range(len(l)-1): 549 | l[i+1] = (l[i] * l[i+1]) % n 550 | 551 | try: 552 | inv = invert(l[-1], n) 553 | except ZeroDivisionError: 554 | inv = 0 555 | if inv == 0: 556 | return gcd(l[-1], n) 557 | 558 | for i in range(len(l)-1, 0, -1): 559 | l[i] = (inv * l[i-1]) % n 560 | inv = (inv * l_[i]) % n 561 | l[0] = inv 562 | 563 | return l 564 | 565 | def prod(p): 566 | '''Multiplies all elements of a list together. The order in which the 567 | elements are multiplied is chosen to take advantage of Python's Karatsuba 568 | Multiplication 569 | 570 | Returns the product of everything in p.''' 571 | jump = 1 572 | 573 | while jump < len(p): 574 | for i in range(0, len(p) - jump, jump << 1): 575 | p[i] *= p[i + jump] 576 | p[i + jump] = None 577 | 578 | jump <<= 1 579 | 580 | return p[0] 581 | 582 | def rho_ev(x, ts): 583 | '''Evaluates Dickman's rho function, which calculates the asymptotic 584 | probability as N approaches infinity (for a given x) that all of N's factors 585 | are bounded by N^(1/x).''' 586 | return ts[int(x)].ev(x - int(x) - 0.5) 587 | 588 | def rho_ts(n): 589 | '''Makes a list of Taylor series for the rho function centered at 0.5, 1.5, 2.5 ... n + 0.5. The reason this is necessary is that the radius of convergence of rho is small, so we need lots of Taylor series centered at different places to correctly evaluate it. 590 | 591 | Returns a list of Taylor series.''' 592 | f = ts(10, 10, []) 593 | answer = [ts(10, 10, [1])] 594 | for _ in range(n): 595 | answer.append(ts(10, 10, [1])) 596 | deg = 5 597 | acc = 50 + n * int(1 + math.log(1 + n) + math.log(math.log(3 + n))) 598 | r = 1 599 | rho_series = ts(1, 10, [0]) 600 | while r != rho_series.coefficients[0]: 601 | deg = (deg + (deg << 2)) // 3 602 | r = rho_series.coefficients[0] 603 | rho_series = ts(deg, acc, [(1) << acc]) 604 | center = 0.5 605 | for i in range(1, n+1): 606 | f.set(rho_series) 607 | center += 1 608 | f.lindiv(int(2*center)) 609 | f.int() 610 | f.neg() 611 | d = ts(deg, acc, [rho_series.evh() - f.evmh()]) 612 | f.add(f, d) 613 | rho_series.set(f) 614 | f.simp() 615 | answer[i].set(f) 616 | rho_series.simp() 617 | 618 | return answer 619 | 620 | def sub_sub_sure_factors(f, u, curve_parameter): 621 | '''Finds all factors that can be found using ECM with a smoothness bound of u and sigma and give curve parameters. If that fails, checks for being a prime power and does Fermat factoring as well. 622 | 623 | Yields factors.''' 624 | while not (f & 1): 625 | yield 2 626 | f >>= 1 627 | 628 | while not (f % 3): 629 | yield 3 630 | f = f // 3 631 | 632 | if isprime(f): 633 | yield f 634 | return 635 | 636 | log_u = math.log(u) 637 | u2 = int(_7_OVER_LOG_2 * u * log_u / math.log(log_u)) 638 | primes = [] 639 | still_a_chance = True 640 | log_mo = math.log(f + 1 + sqrt(f << 2)) 641 | 642 | g = gcd(curve_parameter, f) 643 | if g not in (1, f): 644 | for factor in sub_sub_sure_factors(g, u, curve_parameter): 645 | yield factor 646 | for factor in sub_sub_sure_factors(f//g, u, curve_parameter): 647 | yield factor 648 | return 649 | 650 | g2 = gcd(curve_parameter**2 - 5, f) 651 | if g2 not in (1, f): 652 | for factor in sub_sub_sure_factors(g2, u, curve_parameter): 653 | yield factor 654 | for factor in sub_sub_sure_factors(f // g2, u, curve_parameter): 655 | yield factor 656 | return 657 | 658 | if f in (g, g2): 659 | yield f 660 | 661 | while still_a_chance: 662 | p1 = get_points([curve_parameter], f) 663 | for prime in primes: 664 | p1 = multiply(p1, prime, f) 665 | if not isinstance(p1, list): 666 | if p1 != f: 667 | for factor in sub_sub_sure_factors(p1, u, curve_parameter): 668 | yield factor 669 | for factor in sub_sub_sure_factors(f//p1, u, curve_parameter): 670 | yield factor 671 | return 672 | else: 673 | still_a_chance = False 674 | break 675 | 676 | if not still_a_chance: 677 | break 678 | 679 | prime = 1 680 | still_a_chance = False 681 | while prime < u2: 682 | prime = next_prime(prime) 683 | should_break = False 684 | for _ in range(int(log_mo / math.log(prime))): 685 | p1 = multiply(p1, prime, f) 686 | if not isinstance(p1, list): 687 | if p1 != f: 688 | for factor in sub_sub_sure_factors(p1, u, curve_parameter): 689 | yield factor 690 | for factor in sub_sub_sure_factors(f//p1, u, curve_parameter): 691 | yield factor 692 | return 693 | 694 | else: 695 | still_a_chance = True 696 | primes.append(prime) 697 | should_break = True 698 | break 699 | if should_break: 700 | break 701 | 702 | for i in range(2, int(math.log(f) / LOG_2) + 2): 703 | r = root(f, i) 704 | if r[1]: 705 | for factor in sub_sub_sure_factors(r[0], u, curve_parameter): 706 | for _ in range(i): 707 | yield factor 708 | return 709 | 710 | a = 1 + sqrt(f) 711 | bsq = a * a - f 712 | iter = 0 713 | 714 | while bsq != sqrt(bsq)**2 and iter < 3: 715 | a += 1 716 | iter += 1 717 | bsq += a + a - 1 718 | 719 | if bsq == sqrt(bsq)**2: 720 | b = sqrt(bsq) 721 | for factor in sub_sub_sure_factors(a - b, u, curve_parameter): 722 | yield factor 723 | for factor in sub_sub_sure_factors(a + b, u, curve_parameter): 724 | yield factor 725 | return 726 | 727 | yield f 728 | return 729 | 730 | def sub_sure_factors(f, u, curve_params): 731 | '''Factors n as far as possible using the fact that f came from a mainloop call. 732 | 733 | Yields factors of n.''' 734 | if len(curve_params) == 1: 735 | for factor in sub_sub_sure_factors(f, u, curve_params[0]): 736 | yield factor 737 | return 738 | 739 | c1 = curve_params[:len(curve_params) >> 1] 740 | c2 = curve_params[len(curve_params) >> 1:] 741 | 742 | if mainloop(f, u, c1) == 1: 743 | for factor in sub_sure_factors(f, u, c2): 744 | yield factor 745 | return 746 | 747 | if mainloop(f, u, c2) == 1: 748 | for factor in sub_sure_factors(f, u, c1): 749 | yield factor 750 | return 751 | 752 | for factor in sub_sure_factors(f, u, c1): 753 | if isprime(factor): 754 | yield factor 755 | else: 756 | for factor_of_factor in sub_sure_factors(factor, u, c2): 757 | yield factor_of_factor 758 | 759 | return 760 | 761 | def subtract(p1, p2, n): 762 | '''Given two points on an elliptic curve, subtract them pointwise. 763 | 764 | Returns the resulting point.''' 765 | inv = list(range(len(p1))) 766 | 767 | for i in range(len(p1)): 768 | inv[i] = p2[i][0] - p1[i][0] 769 | 770 | inv = parallel_invert(inv, n) 771 | 772 | if not isinstance(inv, list): 773 | return inv 774 | 775 | for i in range(len(p1)): 776 | m = ((p1[i][1] + p2[i][1]) * inv[i]) % n 777 | p2[i][0] = (m * m - p1[i][0] - p2[i][0]) % n 778 | p2[i][1] = (m * (p1[i][0] - p2[i][0]) + p1[i][1]) % n 779 | 780 | return p2 781 | 782 | def congrats(f, veb): 783 | '''Prints a congratulations message when a record factor is found. This only happens if the second parameter (verbosity) is set to True. 784 | 785 | Returns nothing.''' 786 | 787 | if veb and f > RECORD: 788 | print('Congratulations! You may have found a record factor via pyecm!') 789 | print('Please email the Mainloop call to Eric Larson ') 790 | 791 | return 792 | 793 | def sure_factors(n, u, curve_params, veb, ra, ov, tdb, pr): 794 | '''Factor n as far as possible with given smoothness bound and curve parameters, including possibly (but very rarely) calling ecm again. 795 | 796 | Yields factors of n.''' 797 | f = mainloop(n, u, curve_params) 798 | 799 | if f == 1: 800 | return 801 | 802 | if veb: 803 | print('Found factor:', f) 804 | print('Mainloop call was:', n, u, curve_params) 805 | 806 | if isprime(f): 807 | congrats(f, veb) 808 | yield f 809 | n = n//f 810 | if isprime(n): 811 | yield n 812 | if veb: 813 | print('(factor processed)') 814 | return 815 | for factor in sub_sure_factors(f, u, curve_params): 816 | if isprime(factor): 817 | congrats(f, veb) 818 | yield factor 819 | else: 820 | if veb: 821 | print('entering new ecm loop to deal with stubborn factor:', factor) 822 | for factor_of_factor in ecm(factor, True, ov, veb, tdb, pr): 823 | yield factor_of_factor 824 | n = n//factor 825 | 826 | if isprime(n): 827 | yield n 828 | 829 | if veb: 830 | print('(factor processed)') 831 | return 832 | 833 | def to_tuple(p): 834 | '''Converts a list of two-element lists into a list of two-element tuples. 835 | 836 | Returns a list.''' 837 | answer = [] 838 | for i in p: 839 | answer.append((i[0], i[1])) 840 | 841 | return tuple(answer) 842 | 843 | def mainloop(n, u, p1): 844 | ''' Input: n -- an integer to (try) to factor. 845 | u -- the phase 1 smoothness bound 846 | p1 -- a list of sigma parameters to try 847 | 848 | Output: A factor of n. (1 is returned on faliure). 849 | 850 | Notes: 851 | 1. Other parameters, such as the phase 2 smoothness bound are selected by the mainloop function. 852 | 2. This function uses batch algorithms, so if p1 is not long enough, there will be a loss in efficiency. 853 | 3. Of course, if p1 is too long, then the mainloop will have to use more memory. 854 | [The memory is polynomial in the length of p1, log u, and log n].''' 855 | k = inv_const(n) 856 | log_u = math.log(u) 857 | log_log_u = math.log(log_u) 858 | log_n = math.log(n) 859 | u2 = int(_7_OVER_LOG_2 * u * log_u / log_log_u) 860 | ncurves = len(p1) 861 | w = int(math.sqrt(_3_OVER_LOG_2 * ncurves / k) - 0.5) 862 | number_of_primes = int((ncurves << w) * math.sqrt(LOG_4_OVER_9 * log_n / k) / log_u) # Lagrange multipliers! 863 | number_of_primes = min(number_of_primes, int((log_n / math.log(log_n))**2 * ncurves / log_u), int(u / log_u)) 864 | number_of_primes = max(number_of_primes, 1) 865 | m = math.log(number_of_primes) + log_log_u 866 | w = min(w, int((m - 2 * math.log(m) + LOG_3_MINUS_LOG_LOG_2) / LOG_2)) 867 | w = max(w, 1) 868 | max_order = n + sqrt(n << 2) + 1 # By Hasse's theorem. 869 | det_bound = ((1 << w) - 1 + ((w & 1) << 1)) // 3 870 | log_mo = math.log(max_order) 871 | p = list(range(number_of_primes)) 872 | prime = mpz(2) 873 | p1 = get_points(p1, n) 874 | if not isinstance(p1, list): 875 | return p1 876 | 877 | for _ in range(int(log_mo / LOG_2)): 878 | p1 = double(p1, n) 879 | if not isinstance(p1, list): 880 | return p1 881 | 882 | for i in range(1, det_bound): 883 | prime = (i << 1) + 1 884 | if isprime(prime): 885 | for _ in range(int(log_mo / math.log(prime))): 886 | p1 = multiply(p1, prime, n) 887 | if not isinstance(p1, list): 888 | return p1 889 | 890 | while prime < sqrt(u) and isinstance(p1, list): 891 | for i in range(number_of_primes): 892 | prime = next_prime(prime) 893 | p[i] = prime ** max(1, int(log_u / math.log(prime))) 894 | p1 = fast_multiply(p1, prod(p), n, w) 895 | 896 | if not isinstance(p1, list): 897 | return p1 898 | 899 | while prime < u and isinstance(p1, list): 900 | for i in range(number_of_primes): 901 | prime = next_prime(prime) 902 | p[i] = prime 903 | p1 = fast_multiply(p1, prod(p), n, w) 904 | 905 | if not isinstance(p1, list): 906 | return p1 907 | 908 | del p 909 | 910 | small_jump = int(greatest_n((1 << (w + 2)) // 3)) 911 | small_jump = max(120, small_jump) 912 | big_jump = 1 + (int(sqrt((5 << w) // 21)) << 1) 913 | total_jump = small_jump * big_jump 914 | big_multiple = max(total_jump << 1, ((int(next_prime(prime)) - (total_jump >> 1)) // total_jump) * total_jump) 915 | big_jump_2 = big_jump >> 1 916 | small_jump_2 = small_jump >> 1 917 | product = ONE 918 | 919 | psmall_jump = multiply(p1, small_jump, n) 920 | if not isinstance(psmall_jump, list): 921 | return psmall_jump 922 | 923 | ptotal_jump = multiply(psmall_jump, big_jump, n) 924 | if not isinstance(ptotal_jump, list): 925 | return ptotal_jump 926 | 927 | pgiant_step = multiply(p1, big_multiple, n) 928 | if not isinstance(pgiant_step, list): 929 | return pgiant_step 930 | 931 | small_multiples = [None] 932 | for i in range(1, small_jump >> 1): 933 | if gcd(i, small_jump) == 1: 934 | tmp = multiply(p1, i, n) 935 | if not isinstance(tmp, list): 936 | return tmp 937 | for i in range(len(tmp)): 938 | tmp[i] = tmp[i][0] 939 | small_multiples.append(tuple(tmp)) 940 | else: 941 | small_multiples.append(None) 942 | small_multiples = tuple(small_multiples) 943 | 944 | big_multiples = [None] 945 | for i in range(1, (big_jump + 1) >> 1): 946 | tmp = multiply(psmall_jump, i, n) 947 | if not isinstance(tmp, list): 948 | return tmp 949 | big_multiples.append(to_tuple(tmp)) 950 | big_multiples = tuple(big_multiples) 951 | 952 | psmall_jump = to_tuple(psmall_jump) 953 | ptotal_jump = to_tuple(ptotal_jump) 954 | 955 | while big_multiple < u2: 956 | big_multiple += total_jump 957 | center_up = big_multiple 958 | center_down = big_multiple 959 | pgiant_step = add(ptotal_jump, pgiant_step, n) 960 | if not isinstance(pgiant_step, list): 961 | return pgiant_step 962 | 963 | prime_up = next_prime(big_multiple - small_jump_2) 964 | while prime_up < big_multiple + small_jump_2: 965 | s = small_multiples[abs(int(prime_up) - big_multiple)] 966 | for j in range(ncurves): 967 | product *= pgiant_step[j][0] - s[j] 968 | product %= n 969 | prime_up = next_prime(prime_up) 970 | 971 | for i in range(1, big_jump_2 + 1): 972 | center_up += small_jump 973 | center_down -= small_jump 974 | 975 | pmed_step_up, pmed_step_down = add_sub_x_only(big_multiples[i], pgiant_step, n) 976 | if pmed_step_down == None: 977 | return pmed_step_up 978 | 979 | while prime_up < center_up + small_jump_2: 980 | s = small_multiples[abs(int(prime_up) - center_up)] 981 | for j in range(ncurves): 982 | product *= pmed_step_up[j] - s[j] 983 | product %= n 984 | prime_up = next_prime(prime_up) 985 | 986 | prime_down = next_prime(center_down - small_jump_2) 987 | while prime_down < center_down + small_jump_2: 988 | s = small_multiples[abs(int(prime_down) - center_down)] 989 | for j in range(ncurves): 990 | product *= pmed_step_down[j] - s[j] 991 | product %= n 992 | prime_down = next_prime(prime_down) 993 | 994 | if gcd(product, n) != 1: 995 | return gcd(product, n) 996 | 997 | return 1 998 | 999 | def fast_multiply(p, d, n, w): 1000 | '''Multiplies each element of p by d. Multiplication is on 1001 | an elliptic curve. Both d and

must be odd. Also,

may not be divisible by anything less than or equal to 2 * (2**w + (-1)**w) / 3 + 1. 1002 | 1003 | Returns the list p multiplied by d.''' 1004 | 1005 | mask = (1 << (w << 1)) - 1 1006 | flop = mask // 3 1007 | g = naf(d) >> 4 1008 | precomp = {} 1009 | m = copy(p) 1010 | p = double(p, n) 1011 | 1012 | for i in range((flop >> w) + (w & 1)): 1013 | key = naf((i << 1) + 1) 1014 | precomp[key] = to_tuple(m) 1015 | precomp[((key & flop) << 1) ^ key] = precomp[key] 1016 | m = add(p, m, n) 1017 | 1018 | while g > 0: 1019 | if g & 1: 1020 | t = g & mask 1021 | sh = 1 + int(math.log(t) / LOG_4) 1022 | for _ in range(sh): 1023 | p = double(p, n) 1024 | 1025 | if g & 2: 1026 | p = subtract(precomp[t], p, n) 1027 | else: 1028 | p = add(precomp[t], p, n) 1029 | 1030 | g >>= (sh << 1) 1031 | if not isinstance(p, list): 1032 | return p 1033 | else: 1034 | p = double(p, n) 1035 | g >>= 2 1036 | 1037 | return p 1038 | 1039 | def get_points(p1, n): 1040 | '''Outputs points in Weierstrass form, given input in Suyama 1041 | parametrization. 1042 | 1043 | Returns the points.''' 1044 | p1 = list(p1) 1045 | invs = p1[:] 1046 | ncurves = len(p1) 1047 | 1048 | for j in range(ncurves): 1049 | sigma = mpz(p1[j]) 1050 | u = (sigma**2 - 5) % n 1051 | v = sigma << 2 1052 | i = (((u * u) % n) * ((v * u << 2) % n)) % n 1053 | p1[j] = [u, v, i] 1054 | invs[j] = (i * v) % n 1055 | 1056 | invs = parallel_invert(invs, n) 1057 | if not isinstance(invs, list): 1058 | return invs 1059 | 1060 | for j in range(ncurves): 1061 | u, v, i = p1[j] 1062 | inv = invs[j] 1063 | 1064 | a = (((((((v - u)**3 % n) * v) % n) * (u + u + u + v)) % n) * inv - 2) % n # <-- This line is a thing of beauty 1065 | x_0 = (((((u * i) % n) * inv) % n) ** 3) % n # And this one gets second place 1066 | b = ((((x_0 + a) * x_0 + 1) % n) * x_0) % n 1067 | x_0 = (b * x_0) % n 1068 | y_0 = (b**2) % n 1069 | 1070 | while a % 3: 1071 | a += n 1072 | 1073 | x_0 = (x_0 + a * b // 3) % n 1074 | c = (y_0 * ((1 - a**2 // 3) % n)) % n 1075 | 1076 | p1[j] = [x_0, y_0, c] 1077 | 1078 | return p1 1079 | 1080 | def isprime(n): 1081 | ''' Tests for primality of n trying first fastprime and then a slower but accurate algorithm. Time complexity is O(N**3) (assuming quadratic multiplication), where n has N digits. 1082 | 1083 | Returns the primality of n (True or False).''' 1084 | if not fastprime(n): 1085 | return False 1086 | elif n < SMALLEST_COUNTEREXAMPLE_FASTPRIME: 1087 | return True 1088 | 1089 | do_loop = False 1090 | j = 1 1091 | d = n >> 1 1092 | a = 2 1093 | bound = int(0.75 * math.log(math.log(n)) * math.log(n)) + 1 1094 | 1095 | while not d & 1: 1096 | d >>= 1 1097 | j += 1 1098 | 1099 | while a < bound: 1100 | a = next_prime(a) 1101 | p = atdn(a, d, n) 1102 | 1103 | if p == 1 or p == n - 1: 1104 | continue 1105 | 1106 | for _ in range(j): 1107 | p = (p * p) % n 1108 | 1109 | if p == 1: 1110 | return False 1111 | elif p == n - 1: 1112 | do_loop = True 1113 | break 1114 | 1115 | if do_loop: 1116 | do_loop = False 1117 | continue 1118 | 1119 | return False 1120 | 1121 | return True 1122 | 1123 | def multiply(p1, d, n): 1124 | '''Multiplies each element of a list by a number, without using too much overhead. 1125 | 1126 | Returns a list p multiplied through by d.''' 1127 | pos = int(math.log(d) / LOG_2) - 1 1128 | p = copy(p1) 1129 | 1130 | while pos >= 0: 1131 | p = double(p, n) 1132 | if not isinstance(p, list): 1133 | return p 1134 | if (d >> pos) & 1: 1135 | p = add(p1, p, n) 1136 | if not isinstance(p, list): 1137 | return p 1138 | pos -= 1 1139 | 1140 | return p 1141 | 1142 | def ecm(n, ra, ov, veb, tdb, pr): # DOCUMENTATION 1143 | '''Input: 1144 | n -- An integer to factor 1145 | veb -- If True, be verbose 1146 | ra -- If True, select sigma values randomly 1147 | ov -- How asymptotically fast the calculation is 1148 | pr -- What portion of the total processing power this run gets 1149 | 1150 | Output: Factors of n, via a generator. 1151 | 1152 | Notes: 1153 | 1. A good value of ov for typical numbers is somewhere around 10. If this parameter is too high, overhead and memory usage grow. 1154 | 2. If ra is set to False and veb is set to True, then results are reproducible. If ra is set to True, then one number may be done in parallel on disconnected machines (at only a small loss of efficiency, which is less if pr is set correctly).''' 1155 | 1156 | if veb: 1157 | looking_for = 0 1158 | k = inv_const(n) 1159 | 1160 | if ra: 1161 | sigma = 6 + random.randrange(BILLION) 1162 | else: 1163 | sigma = 6 1164 | 1165 | for factor in sure_factors(n, k, list(range(sigma, sigma + k)), veb, ra, ov, tdb, pr): 1166 | yield factor 1167 | n = n//factor 1168 | 1169 | if n == 1: 1170 | return 1171 | 1172 | if ra: 1173 | sigma += k + random.randrange(BILLION) 1174 | else: 1175 | sigma += k 1176 | 1177 | x_max = 0.5 * math.log(n) / math.log(k) 1178 | t = rho_ts(int(x_max)) 1179 | prime_probs = [] 1180 | nc = 1 + int(_12_LOG_2_OVER_49 * ov * ov * k) 1181 | eff_nc = nc / pr 1182 | 1183 | for i in range(1 + (int(math.log(n)) >> 1)): 1184 | if i < math.log(tdb): 1185 | prime_probs.append(0) 1186 | else: 1187 | prime_probs.append(1.0/i) 1188 | 1189 | for i in range(len(prime_probs)): 1190 | p_success = rho_ev((i - 2.65) / math.log(k), t) 1191 | p_fail = max(0, (1 - p_success * math.log(math.log(k)))) ** (k / pr) 1192 | prime_probs[i] = p_fail * prime_probs[i] / (p_fail * prime_probs[i] + 1 - prime_probs[i]) 1193 | 1194 | while n != 1: 1195 | low = int(k) 1196 | high = n 1197 | while high > low + 1: 1198 | u = (high + low) >> 1 1199 | sum = 0 1200 | log_u = math.log(u) 1201 | for i in range(len(prime_probs)): 1202 | log_p = i - 2.65 1203 | log_u = math.log(u) 1204 | quot = log_p / log_u 1205 | sum += prime_probs[i] * (rho_ev(quot - 1, t) - rho_ev(quot, t) * log_u) 1206 | if sum < 0: 1207 | high = u 1208 | else: 1209 | low = u 1210 | 1211 | if ra: 1212 | sigma += nc + random.randrange(BILLION) 1213 | else: 1214 | sigma += nc 1215 | 1216 | for factor in sure_factors(n, u, list(range(sigma, sigma + nc)), veb, ra, ov, tdb, pr): 1217 | yield factor 1218 | n = n // factor 1219 | 1220 | for i in range(len(prime_probs)): 1221 | p_success = rho_ev((i - 2.65) / math.log(u), t) 1222 | p_fail = max(0, (1 - p_success * math.log(math.log(u)))) ** eff_nc 1223 | prime_probs[i] = p_fail * prime_probs[i] / (p_fail * prime_probs[i] + 1 - prime_probs[i]) 1224 | prime_probs = prime_probs[:1 + (int(math.log(n)) >> 1)] 1225 | 1226 | if veb and n != 1: 1227 | m = max(prime_probs) 1228 | for i in range(len(prime_probs)): 1229 | if prime_probs[i] == m: 1230 | break 1231 | 1232 | new_looking_for = (int(i / _5_LOG_10) + 1) 1233 | new_looking_for += new_looking_for << 2 1234 | if new_looking_for != looking_for: 1235 | looking_for = new_looking_for 1236 | print('Searching for primes around', looking_for, 'digits') 1237 | 1238 | return 1239 | 1240 | def factors(n, veb, ra, ov, pr): 1241 | '''Generates factors of n. 1242 | Strips small primes, then feeds to ecm function. 1243 | 1244 | Input: 1245 | n -- An integer to factor 1246 | veb -- If True, be verbose 1247 | ra -- If True, select sigma values randomly 1248 | ov -- How asymptotically fast the calculation is 1249 | pr -- What portion of the total processing power this run gets 1250 | 1251 | Output: Factors of n, via a generator. 1252 | 1253 | Notes: 1254 | 1. A good value of ov for typical numbers is somewhere around 10. If this parameter is too high, overhead and memory usage grow. 1255 | 2. If ra is set to False and veb is set to True, then results are reproducible. If ra is set to True, then one number may be done in parallel on disconnected machines (at only a small loss of efficiency, which is less if pr is set correctly).''' 1256 | 1257 | 1258 | if type(n) not in T: 1259 | raise ValueError('Number given must be integer or long.') 1260 | 1261 | if n == 0: 1262 | raise ValueError('Number given must be greater than 0.') 1263 | 1264 | if not 0 < pr <= 1: 1265 | yield 'Error: pr must be between 0 and 1' 1266 | return 1267 | 1268 | while not n & 1: 1269 | n >>= 1 1270 | yield mpz(2) 1271 | 1272 | n = mpz(n) 1273 | k = inv_const(n) 1274 | prime = 2 1275 | trial_division_bound = max(10 * k**2, 100) 1276 | 1277 | while prime < trial_division_bound: 1278 | prime = next_prime(prime) 1279 | while not n % prime: 1280 | n = n//prime 1281 | yield prime 1282 | 1283 | if isprime(n): 1284 | yield n 1285 | return 1286 | 1287 | if n == 1: 1288 | return 1289 | 1290 | for factor in ecm(n, ra, ov, veb, trial_division_bound, pr): 1291 | yield factor 1292 | 1293 | ### End of algorithm code; beginning of interface code ## 1294 | 1295 | def is_switch(s): 1296 | '''Tests whether the input string is a switch (e.g. "-v" or "--help"). 1297 | 1298 | Returns True or False.''' 1299 | 1300 | for i in range(len(s)): 1301 | if s[i] != '-': 1302 | break 1303 | 1304 | if i == 0: # s not begin with "-" 1305 | return False 1306 | for char in s[i:]: 1307 | if not char.isalpha(): 1308 | if char == '=': # Switches like "--portion=" are acceptable 1309 | return True 1310 | else: 1311 | return False 1312 | return True 1313 | 1314 | def parse_switch(s, switch): 1315 | '''Parses a switch in the form '--string=num' and returns num or calls help() if the string is invalid. 1316 | 1317 | Returns the num in '--string=num'.''' 1318 | 1319 | try: 1320 | return float(s[len(switch) + 3:]) 1321 | except ValueError: 1322 | help() 1323 | 1324 | def valid_input(s): 1325 | '''Tests the input string for validity as a mathematical expressions. 1326 | 1327 | Returns True or False.''' 1328 | valid = ('(', ')', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/', '^', ' ', '\t') 1329 | 1330 | for char in s: 1331 | if char not in valid: 1332 | return False 1333 | 1334 | return True 1335 | 1336 | def help(): 1337 | print( '''\ 1338 | Usage: pyecm [OPTION] [expression to factor] 1339 | Factor numbers using the Elliptic Curve Method. 1340 | 1341 | --portion=num Does only part of the work for factoring, corresponding to 1342 | what fraction of the total work the machine is doing. Useful for working in 1343 | parallel. For example, if there are three machines: 1GHz, 1GHz, and 2GHz, print 1344 | should be set to 0.25 for the 1GHz machines and 0.5 for the 2GHz machine. 1345 | Implies -r and -v. -r is needed to avoid duplicating work and -v is needed to 1346 | report results. 1347 | --ov=num Sets the value of the internal parameter ov, which 1348 | determines the trade-off between memory and time usage. Do not touch if you do 1349 | not know what you are doing. Please read all the documentation and understand 1350 | the full implications of the parameter before using this switch. 1351 | -n, --noverbose Terse. On by default. Needed to cancel the -v from the 1352 | --portion or --random switches. If both -n and -v are specified, the one 1353 | specified last takes precedence. 1354 | -r, --random Chooses random values for sigma, an internal parameter in 1355 | the calculation. Implies -v; if you're doing something random, you want to know 1356 | what's happening. 1357 | -v, --verbose Explains what is being done with intermediate calculations 1358 | and results. 1359 | 1360 | With no integers to factor given via command-line, read standard input. 1361 | 1362 | Please report bugs to Eric Larson .''') 1363 | sys.exit() 1364 | 1365 | def command_line(veb, ra, ov, pr): 1366 | l = len(sys.argv) 1367 | for i in range(1, l): 1368 | if not is_switch(sys.argv[i]): 1369 | break 1370 | 1371 | for j in range(i, l): # Start with the first non-switch 1372 | if j != i: # Pretty printing 1373 | print( '') 1374 | response = sys.argv[j] 1375 | if valid_input(response): 1376 | response = response.replace('^', '**') 1377 | try: 1378 | n = eval(response) 1379 | int(n) 1380 | except (SyntaxError, TypeError, ValueError): 1381 | help() 1382 | else: 1383 | help() 1384 | 1385 | print('Factoring {0}:'.format(n)) 1386 | if n < 0: 1387 | print(-1) 1388 | n = -n 1389 | if n == 0: 1390 | print( '0 does not have a well-defined factorization.') 1391 | continue 1392 | elif n == 1: 1393 | print( 1) 1394 | continue 1395 | 1396 | if ov == DUMMY: 1397 | ov = 2*math.log(math.log(n)) 1398 | for factor in factors(n, veb, ra, ov, pr): 1399 | print(factor) 1400 | 1401 | def interactive(veb, ra, ov, pr): 1402 | print('pyecm v. {0} (interactive mode):'.format(VERSION)) 1403 | print('Type "exit" at any time to quit.') 1404 | print() 1405 | 1406 | user_input = input() 1407 | while user_input != 'exit' and user_input != 'quit': 1408 | if valid_input(user_input): 1409 | user_input = user_input.replace('^', '**') 1410 | try: 1411 | n = eval(user_input) 1412 | int(n) 1413 | except (SyntaxError, TypeError, ValueError): 1414 | help() 1415 | else: 1416 | help() 1417 | 1418 | print('Factoring number %d:' % n) 1419 | if n < 0: 1420 | print( -1) 1421 | n = -n 1422 | if n == 0: 1423 | print('0 does not have a well-defined factorization.') 1424 | print() 1425 | user_input = input() 1426 | continue 1427 | elif n == 1: 1428 | print(1) 1429 | print() 1430 | user_input = input() 1431 | continue 1432 | 1433 | if ov == DUMMY: 1434 | ov = 2*math.log(math.log(n)) 1435 | for factor in factors(n, veb, ra, ov, pr): 1436 | print(factor) 1437 | print() 1438 | user_input = input() 1439 | 1440 | def main(): 1441 | ra = veb = False 1442 | pr = 1.0 1443 | ov = DUMMY 1444 | for item in sys.argv[1:]: 1445 | if item == '--help': 1446 | help() 1447 | elif item == '--noverbose': 1448 | veb = False 1449 | elif item == '--random': 1450 | ra = veb = True 1451 | elif item == '--verbose': 1452 | veb = True 1453 | elif item[:10] == '--portion=': 1454 | pr = parse_switch(item, 'portion') 1455 | ra = veb = True 1456 | elif item[:5] == '--ov=': 1457 | ov = parse_switch(item, 'ov') 1458 | elif len(item) >= 2 and item[0] == '-' and item[1] != '-': # Short switch 1459 | for char in item: 1460 | if char == 'h': 1461 | help() 1462 | elif char == 'n': 1463 | veb = False 1464 | elif char == 'r': 1465 | ra = veb = True 1466 | elif char == 'v': 1467 | veb = True 1468 | else: 1469 | if not valid_input(item): 1470 | print('I am confused about the following: "{0}". Here\'s the help page:'.format(item)) 1471 | print() 1472 | help() 1473 | 1474 | if len(sys.argv) > 1 and not is_switch(sys.argv[-1]): 1475 | command_line(veb, ra, ov, pr) 1476 | else: 1477 | interactive(veb, ra, ov, pr) 1478 | 1479 | if __name__ == '__main__': 1480 | try: 1481 | main() 1482 | except (EOFError, KeyboardInterrupt): 1483 | sys.exit() 1484 | --------------------------------------------------------------------------------