Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
indexerror and optimization
#1
Hello! I am new around here and trying to solve some basic challenges.
I wrote a code for getting prime factors for a number but got (IndexError: list index out of range).
while the code still runs for smaller numbers, it's very badly optimised so large numbers never get answers.
I need help in figuring out the error and the optimisations. Thanks in advance!
here's the code:
x=int(input())
y=1
flag=1
k=[]
for y in range(1,x):
    for z in range(2,y):
        if(y==2)or(y%z!=0):
            flag=1
        else:
            flag=0
            break

    if(flag==1)and(y!=1):
        k.append(y)

for p in range (0,x):
    if(x%k[p]==0):
        print(k[p])
Reply
#2
Please post the error code, in it's entirety, between the error tags. This helps in determining where the problem lies.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#3
(Jan-19-2018, 03:40 PM)sparkz_alot Wrote: Please post the error code, in it's entirety, between the error tags. This helps in determining where the problem lies.

Error:
123 3 41 Traceback (most recent call last): File "/home/atharva/PycharmProjects/untitled/ad.py", line 17, in <module> if(x%k[p]==0): IndexError: list index out of range
This was the error, but I sorted it by using
for p in range (0,len(k)):
at line 16.
The optimisation problem still persists.
If I enter something like 12212, I get an answer. But something like 600851475143 just takes too long(still running) that number is the problem input. Thanks for the reply.
Reply
#4
Print 'k' before the last for loop to see what it contains. 'x' too.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
The reason you are being asked to do such a large number is specifically because brute force methods like this won't work. You are required to come up with a more efficient method.

One relatively efficient method would be to find all possible prime factors that are less than or equal to the square root of the number. Then check only those numbers.

First look up how to write a prime sieve (Eratosthenes will work). Then for each number in the sieve check if it is a factor and divide the number if so.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020