Euler Euler Problem No. 4

n = 0 for a in xrange(999, 100, -1): for b in xrange(a, 100, -1): x = a * b if x > n: s = str(a * b) if s == s[::-1]: n = a * b print n 

I have a question about this solution to the problem . I know this is correct, but I wonder why in xrange(999,100,-1) -1 exists for a and b for loops. Please explain. I'm new to this :)

+4
source share
8 answers

The third parameter, xrange() , is the increment value. The default value is 1, which means that the counter will be counted in ascending direction. To count in a decreasing direction, use -1. Your counter a will go from 999 to 101 (the iterator xrange() stops just before it reaches the second value of the parameter).

xrange() documentation later.

+7
source

-1 indicates a negative step. Thus, the transition from 999 to 100 (excluding).

+5
source

xrange function takes three arguments: start , stop and step . It returns a range of numbers, starting with start , continuing with stop , but not including it. If "start" is greater than stop , a negative step must be provided.

So basically xrange(999, 100, -1) will give you [999, 998, ..., 101]

+1
source

This means that you are decreasing (hence the negative sign) in increments of 1, from 999 to 100

0
source

This is what I got for the Euler # 4 project:

 def Palindrome(s): if s == s[::-1]: return True else: return False i = 100 j = 100 greatest = 0 while (i <= 999): while (j <= 999): product = i * j if (product > greatest and Palindrome(str(product))): greatest = product j += 1 j = 100 i += 1 print "Answer: " + str(greatest) 

-M1K3

0
source

My Python solution:

 container = [] for i in range(100, 999): for j in range(100, 999): num = i * j if str(num) == str(num)[::-1]: container.append(num) print(max(container)) 
0
source

The negative is the modifier. Basically, loops start at 999, end at 100, and get there, changing each number to negative.

-1
source
 for x in range(100, 1000): for y in range(100, 1000): product = x*y if product > x*y: break if str(product) == str(product)[::-1] and product > 900000: print (x, y, product) 
-1
source

All Articles