Python Forum

Full Version: How do I stop this fast factorization program from printing beyond the 3rd output?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a problem with this python37 code during printing and I would like it not to print out beyond the 3rd print statement of the loop. The program is super fast for a factorization program if I can only have a number (print_factors(f)) to print just below the 4th output when needed.

For example 3 prints like this:

The factors of 3 are: 1, 3

If I input 2047 it prints like this:

The factors of 2047 are: 1, 23, 89, 2047

However I would just like it to show up to 89. Here is the code:

You can get some points if you answer this at stackexchange:

https://stackoverflow.com/questions/5922...-3rd-outpu


import math
while True:
    def print_factors(x):
       print("The factors of",x,"are:")
       for i in range(1,x+1):
           if x % i == 0:
               print(i)
               


    p = int(input('Enter a prime number and if the output is 1 and itself its prime: '))
    
   
    k = ((p**2*2))
    l = (((pow(2, k + 1, 2 * k) - 1) % (2 * k)))
    f = (k//2//p)
    print_factors(f)
You can generate factors and slice the iterator
import itertools as itt

def gen_factors(x):
    for i in range(i, x + 1):
        if n % i == 0:
            yield i

def print_factors(x, maxcnt=None):
    g = gen_factors(x)
    if maxcnt is not None:
        g = itt.islice(g, 0, maxcnt)
    for f in g:
        print(f)
...
if __name__ == '__main__':
    print_factors(f, 3)
@Gribouillis

I get this error when I use your code straight out of the box.

print_factors(f, 3)
NameError: name 'f' is not defined


Also maybe there is a way to suppress the primes and just print the composites up the 3rd output. I don't know how though. :(
Pleiades Wrote:NameError: name 'f' is not defined
You need to define f first.
Gribouillis

I'm having trouble with def f, can you show me please Grib thanks. It's holding up what I would like to see regarding not printing beyond 3.
In the first code, I suppose it's yours, you wrote f = .... You only need to do the same.
(Dec-07-2019, 06:47 PM)Gribouillis Wrote: [ -> ]In the first code, I suppose it's yours, you wrote f = .... You only need to do the same.

Thanks a million I figured it out with your help of course :) Dance

import itertools as itt
while True: 
    def gen_factors(x):
        for i in range(1, x + 1):
            if x % i == 0:
                yield i
     
    def print_factors(x, maxcnt=None):
        g = gen_factors(x)
        if maxcnt is not None:
            g = itt.islice(g, 0, maxcnt)
        for p in g:
            print(p)
    p = int(input('Enter a prime number and if the output is 1 and itself its prime: '))
    p = (2**p-1)
    k = ((p**2*2))
    f = (k//2//p)
    if __name__ == '__main__':
        print_factors(p, 3)