简体   繁体   English

为什么我对项目euler 3的回答不起作用?

[英]Why doesn't my answer to project euler 3 work?

I've been trying to solve project Euler problem #3 for a while now. 我一直试图解决项目欧拉问题#3一段时间了。 The code below still doesn't work the way I want it to. 下面的代码仍然不能按我想要的方式工作。

Question 3: The prime factors of 13195 are 5, 7, 13 and 29. 问题3:13195的主要因素是5,7,13和29。

What is the largest prime factor of the number 600851475143 ? 600851475143的最大主要因素是什么?

 getal = 13195
    x = 2 

    while x in xrange(2,getal):
        if getal % x == 0:
            num = getal / x
            for i in xrange (2,num):
                    if num % i == 0:
                        x += 1
                        break
                    else:
                        print num
        else:
            x += 1
            continue

As you can see I'm running it right now with 13195 for the sake of simplicity, but eventually it should have to work with the bigger number. 正如您所看到的,为了简单起见,我现在正在使用13195运行它,但最终它应该使用更大的数字。

My output is this: 我的输出是这样的:

2639 2639 2639 2639 2639 1885 1885 1885 1015 1015 1015 455 455 455 377
377 377 377 377 377 377 377 377 377 377 203 203 203 203 203 145 145
145 91 91 91 91 91 65 65 65 35 35 35 29 29 29 29 29 29 29 29 29 29 29
29 29 29 29 29 29 29 29 29 29 29 29 29 29

29 goes on for a while longer than I showed. 29比我展示的时间长了一段时间。 I do understand it just prints the number as soon as it has found an "i" that this number cannot be divided by. 我知道它只是在找到“i”时打印出这个数字,这个数字不能被除去。 But I don't know how to prevent it from doing this. 但我不知道如何阻止它这样做。 Because in the end 29 is the right answer, however it should just give this answer once and right away. 因为最终29是正确的答案,但它应该只是立即给出这个答案。

You can simplify your code to the code snippet below. 您可以将代码简化为下面的代码段。 It uses a list to store any candidates and then removes them if they are not prime numbers: 它使用一个列表来存储任何候选者,如果它们不是素数,则删除它们:

import math

getal = 600851475143
x = 2 
candidates = [];
while (x < int(math.sqrt(getal)+1)):    
    if getal % x == 0:                
        candidates.append(x)
        for i in xrange (2,int(math.sqrt(x)+1)):
             if x % i == 0:
                 candidates.remove(x)
                 break        
    x = x + 1
print str(candidates).strip('[]')        

您需要break你的的while当你找到答案。

You are not incrementing 'x' after print num statement. print num语句后,您没有incrementing 'x'

  for i in xrange (2,num):
      if num % i == 0:
         break
      else:
         print num
  x += 1

you should be able to even getrid of second if statement as below 你应该能够甚至getrid第二if语句如下

getal = 13195
x = 2 
while x in xrange(2,getal):
  if getal % x == 0:
      num = getal / x
      for i in xrange (2,num):
          if num % i == 0:
             break
          else:
             print num
  x += 1

The Answer is 6857. You don't have to check from 2 to the number. 答案是6857.您不必检查2号码。 Use the property of primes.Check only up-to the square root of the number that you are checking.You can use my Java Code for reference. 使用prime的属性。仅检查您正在检查的数字的平方根。您可以使用我的Java代码作为参考。

class p3{
public static boolean isprime(long y){
    double sq = Math.sqrt(y);
    long endl =(long) (sq+.5);
    for(long j = 2;j <=endl ;j++)
    {
        if(y%j==0){
        return false;
        }
    }
    return true;
}

public static void main(String []asd){
    long test = 600851475143L;
    long ans =-1;
    double e = Math.sqrt(test);
    long end = (long)(e+1);
    for(long i = 2 ; i <= end ;i++)
    {

        if(test%i==0){
            boolean val = isprime(i);
            if(val){
            ans = i;
            }
        }
    }
    System.out.println(ans);
}
}

If you need any help. 如果您需要任何帮助。 I have solved the problems in Project Euler and have saved them in my github repository. 我已经解决了Project Euler中的问题并将它们保存在我的github存储库中。 You are more than welcome to fork it.The url is: https://github.com/vatsarahul999/ProjectEuler-.git 非常欢迎您来分叉。网址是: https//github.com/vatsarahul999/ProjectEuler-.git

Writing the same code in python. 在python中编写相同的代码。

 def isprime(n):
   if n < 2:
     return False
  if n == 2: 
    return True    

  if not n & 1: 
    return False

   for x in range(3, int(n**0.5)+1, 2):
      if n % x == 0:
        return False
   return True

Now the main program 现在的主要方案

v = 13195
x = 2
while(x*x <= v)
  if(isprime(x)):
       a = x
       while(v%x==0)
           v=v/x;
  x++
  print a

Here's a sample (it can be improved in terms of performance): 这是一个示例(可以在性能方面进行改进):

import math

getal = 600851475143

def prime(number):
    for i in xrange(2, int(math.sqrt(number)) + 1):
        if (number % i) == 0:
            return False
    return True

def prime_factors(number):
    ret = []
    n = number
    primes = []
    for i in [item for item in xrange(2, int(math.sqrt(n)) + 1)]:
        if prime(i):
            primes.append(i)
    for i in primes:
        while n % i == 0:
            ret.append(i)
            n = n / i
    return ret

print prime_factors(getal)

Why is everyone incrementing to find the largest number? 为什么每个人都在增加以找到最大的数字? Decrease!!! 减少!!!

def largestPrime(num):
  from __future__ import division
  for i in xrange(num//2 + 1, 1, -1):
    if num%i == 0 and all([i%j != 0 for j in range(2,i//2 + 1)]):
      return i

you are over complicating, to get all factors 你过度复杂,得到所有因素

getal = 13195
for x in range(2, getal):
    if getal % x == 0:
        print x

this one should use the for loop not a while, to use a while here it would be like this 这个应该使用for循环一段时间,在这里使用一段时间它会是这样的

getal = 13195
x = 2
while x < getal:
    if getal % x == 0:
        print x
    x += 1

you dont need to loop thru the constraints to do the work at the loop level - because you are doing it inside 你不需要循环通过约束来完成循环级别的工作 - 因为你是在里面做的

you are actually very close to getting the right answer, you just need to remove indentation in your else statement to have a for else block: 你实际上非常接近得到正确答案,你只需要在你的else语句中删除缩进以获得for else块:

>>> x = 2
>>> getal = 13195
>>> while x in range(2,getal):
        if getal % x == 0:
            num = getal // x
            for i in range (2,num):
                    if num % i == 0:
                        x += 1
                        break #this will break for loop
            else:#this is the only change, moving the else from an else inside of the for to a for else block
                    print (num)
                    break this will break while loop
        else: 
            x += 1
            continue


29

this is surprising for most people because the for-else statement is not well know but it pretty much means to only run the else block if the for block is not exited with a break. 对于大多数人来说,这是令人惊讶的,因为for-else语句并不是很清楚,但它几乎意味着只有在没有退出for block时才运行else块。

With this in mind, YES, this code works but as a lot of other people said, this is NOT the best way to accomplish this task. 考虑到这一点,是的,这个代码可以工作,但正如很多其他人所说,这不是完成这项任务的最佳方法。 Because @RahulVasta posted a good enough answer already, i wont. 因为@RahulVasta已经发布了一个足够好的答案,我不会。 It is not to say that your logic does not work, but, since this is programming, there are infinite ways to approach a problem and some are better than others. 这并不是说你的逻辑不起作用,但是,由于这是编程,有无限的方法来处理问题,有些方法比其他方法更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM