And managed to solve the easiest Project Euler problem. badass
>>> x = 0
>>> for i in range(1, 1000):
... if i % 3 == 0 or i % 5 == 0:
... x+=i
...
>>> x
233168
I noticed wikipedia had another solution and compared my answer to theirs, and yes, it's right.
I SAY WE SHOULD ALL WORK TOWARDS SOLVING ALL OF THESE.
Also, I've been trying to think of a simple and efficient way to solve problem 5, and I keep getting answers that I know are wrong. :'(
and the website in case you're too stupid to google it: http://projecteuler.net/index.php?section=problems
better than jmv could do badass
also my naive solution for number one is sum([i for i in range(1000) if 0 in (i%3, i%5)]) which is much cooler than yours
the mathy way to do it would be to make use of the fact that the sum of the first n natural numbers is [tex]\frac{n(n+1)}{2}[/tex] so the sum of the multiples of 3 that are less than 1000 would be [tex]3*\frac{n(n+1)}{2}[/tex] where n is [tex]\lfloor \frac{1000}{3} \rfloor = 333[/tex]
so we do the same for five, and those two sums, then subtract all the multiples of 15
that's less work for the computer but also lots more work for the coder so yeah i'll just stick with the first one baddood;
also my profile (http://projecteuler.net/index.php?section=profile&profile=Guff)
i haven't solved any new ones for a bit but for the last couple days i've been working my way through them again and actually keeping all my files and solutions organized this time for future reference
guff is nerding up this place too i see baddood;
i'll do one when i get home
okay i've redone the first ten now and have decent (i.e. less than two seconds to run) solutions for each
also number five is easy peasy if you use euclid's algorithm bassir;
Quote from: andré the giant on January 20, 2009, 09:40:07 AM
okay i've redone the first ten now and have decent (i.e. less than two seconds to run) solutions for each
also number five is easy peasy if you use euclid's algorithm bassir;
ahhhhh i hate you :'(
I MUST TRY AGAIN
I think I've come up with a good solution for number 20. Here's what I typed up, but it's not going to give you the actual answer (of course):
x = str(25373)
g = 0
n = 0
for items in x:
q = int(x[g:g+1])
n+=q
g+=1
print n
I tested it and it works perfectly fine. Didn't include the factorial part because if you can't do that (JMV baddood; ), you shouldn't even bother using a computer.
Quote from: Pancake Persona on January 21, 2009, 04:13:14 AM
q = int(x[g:g+1])
wat goonish
for strings, blah[foo : foo + 1] returns exactly the same thing that blah[foo] does
also you should probably learn how to use list comprehensions because then you could do:
def sum_of_digits(numbar):
return sum([int(digit) for digit in str(numbar)])
or at the very least slim down your for loop a bit by eliminating g:
Quote from: Pancake Persona on January 21, 2009, 04:13:14 AM
x = str(25373)
total = 0
for digit in x:
total += int(digit)
print total
problem 20 is easy for languages with built in bignum support (e.g. python, ruby, and every other language that doesn't SUCK madood;) but 100! is a pretty big number and it would definitely be a bit harder to do this in c
Quote from: andré the giant on January 21, 2009, 06:05:34 AM
wat goonish
for strings, blah[foo : foo + 1] returns exactly the same thing that blah[foo] does
\
or at the very least slim down your for loop a bit by eliminating g:
what matters most is i got it done, albeit through unconventional methods
I just wonder if JMV could actually do any of them
Quote from: Pancake Persona on January 21, 2009, 12:57:22 PM
what matters most is i got it done, albeit through unconventional methods
I just wonder if JMV could actually do any of them
well yeah but given that you've been coding games you should probably have better style baddood;
he did the first one but that was with a lot of help akudood;
maybe he could do it in java n_u
Quote from: andré the giant on January 21, 2009, 01:01:53 PM
well yeah but given that you've been coding games you should probably have better style baddood;
he did the first one but that was with a lot of help akudood;
maybe he could do it in java n_u
games are just heaps and mounds of if statements and not much else, so they really don't help me learn and comprehend everything that i should know by now which i'll admit is shameful goonish
for example, a randomly selected chunk from my most recent project:
if item.falling == False:
item.y += move_y
#If you reach 28 pixels above the starting point, fall
if item.y <item.y_init-30:
item.falling = True
#If you walk off the edge of a platform, fall
if item.y == item.y_init and my_color[0] > 0:
item.falling = True
#If falling... fall. If touching the ground, bring back ability to jump
if item.falling == True:
item.y +=1
if item.y >200:
item.y = 202
item.falling = False
item.y_init = item.y
#If you're on a platform, cease falling
if my_color[0] == 0 and my_color[2] == 0:
item.falling = False
item.y_init = item.y
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == K_w:
move_y = -2
# X controls are inverted because the level moves, not the character.
if event.key == K_d:
move_x = -1
if event.key == K_a:
Quote from: Pancake Persona on January 21, 2009, 01:06:25 PM
games are just heaps and mounds of if statements and not much else, so they really don't help me learn and comprehend everything that i should know by now which i'll admit is shameful goonish
okay so read the official docs baddood;
Quote from: Pancake Persona on January 21, 2009, 01:06:25 PM
for example, a randomly selected chunk from my most recent project:[spoiler] if item.falling == False:
item.y += move_y
#If you reach 28 pixels above the starting point, fall
if item.y <item.y_init-30:
item.falling = True
#If you walk off the edge of a platform, fall
if item.y == item.y_init and my_color[0] > 0:
item.falling = True
#If falling... fall. If touching the ground, bring back ability to jump
if item.falling == True:
item.y +=1
if item.y >200:
item.y = 202
item.falling = False
item.y_init = item.y
#If you're on a platform, cease falling
if my_color[0] == 0 and my_color[2] == 0:
item.falling = False
item.y_init = item.y
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == K_w:
move_y = -2
# X controls are inverted because the level moves, not the character.
if event.key == K_d:
move_x = -1
if event.key == K_a:
[/spoiler]
okay well that mostly seems okay akudood;
More please. :3
okay how many you got now baddood;
i haven't done any new ones yet but i did just redo number 12
my solution takes about 3.5 seconds to run though saddood;
Quote from: FAMY2 on January 22, 2009, 07:41:37 AM
I like seeing how you guys discuss this stuff. saddood;
Learn Python <3
[spoiler]help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
and elif if print
as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not with
def from or yield
del global pass
help> topics
Here is a list of available topics. Enter any topic name to get more help.
ASSERTION DEBUGGING LITERALS SEQUENCEMETHODS2
ASSIGNMENT DELETION LOOPING SEQUENCES
ATTRIBUTEMETHODS DICTIONARIES MAPPINGMETHODS SHIFTING
ATTRIBUTES DICTIONARYLITERALS MAPPINGS SLICINGS
AUGMENTEDASSIGNMENT DYNAMICFEATURES METHODS SPECIALATTRIBUTES
BACKQUOTES ELLIPSIS MODULES SPECIALIDENTIFIERS
BASICMETHODS EXCEPTIONS NAMESPACES SPECIALMETHODS
BINARY EXECUTION NONE STRINGMETHODS
BITWISE EXPRESSIONS NUMBERMETHODS STRINGS
BOOLEAN FILES NUMBERS SUBSCRIPTS
CALLABLEMETHODS FLOAT OBJECTS TRACEBACKS
CALLS FORMATTING OPERATORS TRUTHVALUE
CLASSES FRAMEOBJECTS PACKAGES TUPLELITERALS
CODEOBJECTS FRAMES POWER TUPLES
COERCIONS FUNCTIONS PRECEDENCE TYPEOBJECTS
COMPARISON IDENTIFIERS PRINTING TYPES
COMPLEX IMPORTING PRIVATENAMES UNARY
CONDITIONAL INTEGER RETURNING UNICODE
CONTEXTMANAGERS LISTLITERALS SCOPING
CONVERSIONS LISTS SEQUENCEMETHODS1
help> modules
Please wait a moment while I gather a list of all available modules...
Audio_mac _hotshot fnmatch pydoc_topics
BaseHTTPServer _json formatter pyexpat
Bastion _locale fpformat quopri
CGIHTTPServer _lsprof fractions random
Canvas _multibytecodec ftplib re
Carbon _multiprocessing functools repr
CodeWarrior _random future_builtins resource
ColorPicker _sha256 gc rexec
ConfigParser _sha512 genericpath rfc822
Cookie _socket gensuitemodule rlcompleter
Dialog _sqlite3 gestalt robotparser
DocXMLRPCServer _sre getopt runpy
EasyDialogs _ssl getpass sched
Explorer _strptime gettext select
FileDialog _struct glob sets
Finder _symtable grp setuptools
FixTk _testcapi gzip sgmllib
FrameWork _threading_local hashlib sha
HTMLParser _tkinter heapq shelve
IN _warnings hmac shlex
MacOS _weakref hotshot shutil
MimeWriter abc htmlentitydefs signal
MiniAEFrame aepack htmllib site
Nav aetools httplib smtpd
Netscape aetypes ic smtplib
OSATerminology aifc icglue sndhdr
PixMapWrapper altgraph icopen socket
Queue anydbm idlelib sqlite3
ScrolledText applesingle ihooks sre
SimpleDialog appletrawmain imageop sre_compile
SimpleHTTPServer appletrunner imaplib sre_constants
SimpleXMLRPCServer argvemulator imghdr sre_parse
SocketServer array imp ssl
StdSuites ast imputil stat
StringIO asynchat inspect statvfs
SystemEvents asyncore io string
Terminal atexit itertools stringold
Tix audiodev json stringprep
Tkconstants audioop keyword strop
Tkdnd autoGIL lib2to3 struct
Tkinter base64 linecache subprocess
UserDict bdb locale sunau
UserList bdist_mpkg logging sunaudio
UserString bgenlocations macerrors symbol
_AE binascii macholib symtable
_AH binhex macostools sys
_App bisect macpath syslog
_CF bsddb macresource tabnanny
_CG bsddb185 macurl2path tarfile
_CarbonEvt buildtools mailbox telnetlib
_Cm bundlebuilder mailcap tempfile
_Ctl bz2 markupbase terminalcommand
_Dlg cPickle marshal termios
_Drag cProfile math test
_Evt cStringIO md5 tests
_File calendar mhlib textwrap
_Fm cfmfile mimetools this
_Folder cgi mimetypes thread
_Help cgitb mimify threading
_IBCarbon chunk mmap time
_Icn cmath modulefinder timeit
_LWPCookieJar cmd modulegraph tkColorChooser
_Launch code multifile tkCommonDialog
_List codecs multiprocessing tkFileDialog
_Menu codeop mutex tkFont
_Mlte collections netrc tkMessageBox
_MozillaCookieJar colorsys new tkSimpleDialog
_OSA command nis toaiff
_Qd commands nntplib token
_Qdoffs compileall ntpath tokenize
_Qt compiler nturl2path trace
_Res contextlib numbers traceback
_Scrap cookielib opcode tty
_Snd copy operator turtle
_TE copy_reg optparse types
_Win crypt os unicodedata
__builtin__ csv os2emxpath unittest
__future__ ctypes parser urllib
_abcoll curses pdb urllib2
_ast datetime pickle urlparse
_bisect dbhash pickletools user
_builtinSuites dbm pimp uu
_bytesio decimal pipes uuid
_codecs difflib pkg_resources videoreader
_codecs_cn dircache pkgutil warnings
_codecs_hk dis platform wave
_codecs_iso2022 distutils plistlib weakref
_codecs_jp dl popen2 webbrowser
_codecs_kr doctest poplib whichdb
_codecs_tw dumbdbm posix wsgiref
_collections dummy_thread posixfile xdrlib
_csv dummy_threading posixpath xml
_ctypes easy_install pprint xmllib
_ctypes_test email profile xmlrpclib
_curses encodings pstats xxsubtype
_curses_panel errno pty zipfile
_elementtree exceptions pwd zipimport
_fileio fcntl py2app zlib
_functools filecmp py_compile
_hashlib fileinput pyclbr
_heapq findertools pydoc
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".[/spoiler]
Uhm, so I have a question for the guy in red. Why won't idle open a new window :(
multi3 = range(3, 1000, 3)
multi5 = range(5, 1000, 5)
multi3and5 = range(15, 1000, 15)
sum(multi3) +sum(multi5) - sum(multi3and5)
oh yay.
wait a minute, i can reduce that to one line why am i using variables. baddood;
sum(range(3, 1000, 3)) +sum(range(5, 1000, 5)) - sum(range(15, 1000, 15))
the first time I did that in december I didn't know about the sum function :(
My original solution for the problem.
[spoiler]a = 0
b = 0
guff = 0
for i in range(3, 1000, 3):
a = a+ i
for i in range(5, 1000, 5):
b = b+i
for i in range(15, 1000, 15):
guff = guff+i;
print a+b-guff[/spoiler]
Does anyone know why
a = 0
b = 1
while a <= 100:
c=a
a=b
b=c+b
print b
Doesn't run directly in idle? It was pissing me off because I was all "wtf man, that code is correct" but it wouldn't run. I then saved it and did python ./Euler_2.py and it gave me.
QuoteValenteMac:Euler jamesvalente$ python ./Euler_2.py
1
2
3
5
8
13
21
34
55
89
144
233
Which isn't what the problem is asking for, nor what I coded. I just needed a working sequence first.
And there we go. hocuspocus;
#!/usr/bin/python
# Filename : Euler_2.py
#Find the sum of all the even-valued terms in the sequence which do not exceed four million.
a = 0
b = 1
d = 0
while a <= 4000000:
c=a
a=b
b+=c
if a%2==0:
d+= a
print d
Quote from: andré the giant on January 22, 2009, 06:55:36 AM
okay how many you got now baddood;
i haven't done any new ones yet but i did just redo number 12
my solution takes about 3.5 seconds to run though saddood;
no, i just reworked my solutions to the previous ones to run in ruby
But I'm going to try a couple after I wake up tonight.
Quote from: Pancake Persona on January 22, 2009, 12:49:12 PM
no, i just reworked my solutions to the previous ones to run in ruby
But I'm going to try a couple after I wake up tonight.
i was into ruby for a while but then i gave up on it because it didn't have list comprehensions (yeah sure there are ways to do the same thing in ruby but they take a little more effort and more typing and aren't as pretty >:o) akudood;
but seriously learn about list comprehensions and generator expressions and iterators and blah and blah etc. baddood;
also i rewrote my solution to problem 2:
def fib(n):
fib1 = 0
fib2 = 1
for i in range(n - 1):
fib2, fib1 = fib2 + fib1, fib2
return fib2 if n > 0 else 0
import itertools
print(sum(itertools.takewhile(lambda x: x < 4e6, (fib(n) for n in itertools.count() if n % 3 == 0))))
fuck yes generator expressions akudood;
also i'm using python3
also this guy (http://krenzel.info/?p=85) has a crazy fast implementation of a fibonacci function
i did a test of fib(2**n) for n from 0 to 19 using the one i wrote above and his version:
[spoiler]0: fib1 time: 1.09673e-05, fib2time: 2.14577e-06; ratio: 5.11111
1: fib1 time: 5.96046e-06, fib2time: 1.78814e-05; ratio: 0.333333
2: fib1 time: 5.96046e-06, fib2time: 9.05991e-06; ratio: 0.657895
3: fib1 time: 2.19345e-05, fib2time: 1.00136e-05; ratio: 2.19048
4: fib1 time: 8.10623e-06, fib2time: 2.7895e-05; ratio: 0.290598
5: fib1 time: 1.00136e-05, fib2time: 2.90871e-05; ratio: 0.344262
6: fib1 time: 1.50204e-05, fib2time: 5.22137e-05; ratio: 0.287671
7: fib1 time: 4.31538e-05, fib2time: 1.69277e-05; ratio: 2.5493
8: fib1 time: 6.60419e-05, fib2time: 2.09808e-05; ratio: 3.14773
9: fib1 time: 0.000129938, fib2time: 2.59876e-05; ratio: 5.0
10: fib1 time: 0.000296831, fib2time: 3.79086e-05; ratio: 7.83019
11: fib1 time: 0.000808954, fib2time: 6.81877e-05; ratio: 11.8636
12: fib1 time: 0.00269389, fib2time: 0.000169039; ratio: 15.9365
13: fib1 time: 0.00888014, fib2time: 0.000478983; ratio: 18.5396
14: fib1 time: 0.031538, fib2time: 0.00162387; ratio: 19.4215
15: fib1 time: 0.119242, fib2time: 0.00447392; ratio: 26.6527
16: fib1 time: 0.460428, fib2time: 0.0133159; ratio: 34.5773
17: fib1 time: 1.81237, fib2time: 0.0404069; ratio: 44.8529
18: fib1 time: 10.1864, fib2time: 0.123036; ratio: 82.7918
19: fib1 time: 43.4756, fib2time: 0.384916; ratio: 112.948
[/spoiler]
my solution to number 6:
g = []
x = 0
for i in range(1, 101):
g.append(i**2)
x += i
print x**2 - sum(g)
I'm certain guff will criticize my method of doing it, but I'm willing to learn.
Quote from: Pancake Persona on January 23, 2009, 01:16:32 AM
my solution to number 6:
g = []
x = 0
for i in range(1, 101):
g.append(i**2)
x += i
print x**2 - sum(g)
I'm certain guff will criticize my method of doing it, but I'm willing to learn.
it's not bad but as i've said before USE LIST COMPREHENSIONS
also it's kind of weird that for x you just use an int but for g you use a list
this would be more consistent:
x, g = 0, 0
for i in range(1, 101):
g += i ** 2
x += i
print x**2 - g
but anyways what i did was something more like print(sum(i for i in range(101)) ** 2 - sum(i ** 2 for i in range(101)))
also if you want to do it all maths-like, then print(sum(i**3 - i**2 for i in range(101))) is prettier and also works akudood;
Quote from: andré the giant on January 23, 2009, 04:45:40 AM
it's not bad but as i've said before USE LIST COMPREHENSIONS
also it's kind of weird that for x you just use an int but for g you use a list
i don't know why i did it, but it's probably because i just slapped together something in 15 seconds and didn't bother thinking about alternative (and superior) methods
both of you still need to learn list comprehensions baddood;
Quote from: andré the giant on January 23, 2009, 01:39:27 PM
both of you still need to learn list comprehensions baddood;
help me understand better badass
Quote from: Pancake Persona on January 23, 2009, 01:40:32 PM
help me understand better badass
they're not all that complicated what don't you get akudood;
So I've been working with MIPS assembly recently and you've inspired me to try some of the PE problems with it. I solved the first two, but I've run into a bit of a problem in that the assembler I'm using doesn't actually have all the MIPS opcodes built into it and I'd really like to be able to use bitwise logic operations so I might have to find a new assembler.
oh shit of course he has to show up
at least i can still beat lawlz and jmv baddood;
so im on problem 3 and i think i did it right after some help on factorization and lists since i never used them.
now my code is taking a long time to run i hope it works ^___^
Quote from: JMV on January 23, 2009, 05:59:54 PM
...after some help...
AND I HAVE THE IM LOGS TO PROVE IT akudood;
Quote from: andré the giant on January 23, 2009, 05:57:33 PM
oh shit of course he has to show up
at least i can still beat lawlz and jmv baddood;
You've solved like twice as many PE problems as I have. akudood;
Quote from: Gladjaframpf on January 23, 2009, 06:10:54 PM
You've solved like twice as many PE problems as I have. akudood;
yeah but i've had an account for a while now and i'm not using assembly language
QuoteOverflowError: long int too large to convert to int
akudood; akudood; akudood; akudood;
#!/usr/bin/python
# Filename : Euler_003.py
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143?
EUL = 600851475143
#Function for finding primes
def isPrime(n):
import math
if n<2:
return False #Negative Numbers, 0, and 1 are not prime.
elif n==2:
return True #2 is Prime
elif n%2==0:
return False #Even numbers, other than 2, are not prime.
else:
for i in range(3, int(math.sqrt(n))+1,2):
if n%i==0:
return False #Number is composite
else:
return True #All others are prime
#Find Factors
factor_list = []
primeFactors = []
i = 3
while True:
if EUL%i==0:
while EUL % i == 0:
EUL /= i
factor_list.append(i)
if EUL == 1:
break
i+=2
#Take the list of factors and keep only the prime factors.
for factor in factor_list:
if isPrime(factor):
primeFactors.append(factor)
print max(primeFactors)
giggle;
Quote from: andré the giant on January 23, 2009, 06:13:15 PM
yeah but i've had an account for a while now and i'm not using assembly language
I actually did most of the problems I've done sometime last fall in Scheme.
Assembly isn't that bad for the easier ones, but it gets really messy when you need anything complicated. Function calls are horrible because you have to handle all the memory allocation manually.
Quote from: andré the giant on January 23, 2009, 05:57:33 PM
at least i can still beat jmv baddood;
i think anyone can goonish
Quote from: Pancake Persona on January 24, 2009, 02:11:30 AM
i think anyone can goonish
because lack of actually doing the programs because I don't care enough = lack of ability. psyduck;
Quote from: Pancake Persona on January 24, 2009, 02:11:30 AM
i think anyone can goonish
jmv is actually doing okay for a beginner but what's your excuse akudood;
Quote from: andré the giant on January 24, 2009, 10:40:52 AM
jmv is actually doing okay for a beginner but what's your excuse akudood;
laziness and the vidya and a highly irregular sleep schedule that keeps me from ever being able to focus and apply myself to anything
And if anything, JMV should be the "professional" here since he is (or was) studying to be a computer scientist. I just slowly picked up Python over the summer. :O
Just did problem 48 n_u
#!/usr/bin/python
# Filename : Euler_048.py
#Find the last ten digits of the series, 1**1 + 2**2 + 3**3 + ... + 1000**1000
result = 0
for i in range(1,1001):
result+= i**i
print str(result)[-10:]
Quote from: Pancake Persona on January 24, 2009, 10:58:02 AMAnd if anything, JMV should be the "professional" here since he is (or was) studying to be a computer scientist. I just slowly picked up Python over the summer. :O
Because knowing one language makes you a professional in every programming language.
Write a compiler for Java so you don't have to use the JVM, since you know python and that makes you a professional in any language.
Also, as you said, my problem is:
Quote
laziness and the vidya and a highly irregular sleep schedule that keeps me from ever being able to focus and apply myself to anything
Quote from: JMV on January 24, 2009, 11:04:23 AM
Because knowing one language makes you a professional in every programming language.
when did i say we had to solve these in python
my solution for 48:x = str(sum(i**i for i in range(1, 1001)))
print x[-10:]
Looks like JMV got a whoopin', and I thought of guff when I worked towards this clean solution baddood;
Quote from: Pancake Persona on January 24, 2009, 11:18:57 AM
my solution for 48:x = str(sum(i**i for i in range(1, 1001)))
print x[-10:]
Looks like JMV got a whoopin', and I thought of guff when I worked towards this clean solution baddood;
yours is still silly
there's no need whatsoever to assign it to a variable and then have a separate line to print the answer:
print str(sum(i**i for i in range(1, 1001)))[-10:]
would make more sense while still sticking to your method
but my solution is still more than ten times faster:
print(sum(pow(i, i, 10**10) for i in range(1, 1001)) % 10 ** 10)
akudood;
Quote from: andré the giant on January 24, 2009, 11:28:26 AM
yours is still silly
there's no need whatsoever to assign it to a variable and then have a separate line to print the answer:
print str(sum(i**i for i in range(1, 1001)))[-10:]
would make more sense while still sticking to your method
but my solution is still more than ten times faster:
print(sum(pow(i, i, 10**10) for i in range(1, 1001)) % 10 ** 10)
akudood;
well then i learned some more today
oh god i just realized the link in my first post wasn't even to my profile but i fixed it now
also jamie solved problem 4 baddood;
#!/usr/bin/python
# Filename : Euler_006.py
#Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
sumOfSquares, squareOfSums = 0, 0
for i in range(1,101):
sumOfSquares+= i**2
squareOfSums+=i
print squareOfSums**2 - sumOfSquares
Well, my original code was
#!/usr/bin/python
# Filename : Euler_006.py
#Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
sumOfSquares=0
squareOfSums = 0
Sums = 0
for i in range(1,101):
sumOfSquares+= i**2
Sums+=i
squareOfSums=Sums**2
print squareOfSums - sumOfSquares
because I didn't know you could do math in the print statement, but other than that it was close to what guff had.
Quote from: JMV on January 24, 2009, 06:52:29 PM
...but other than that it was close to what guff had.
uh no i had a one liner akudood;
the long code i had wasn't anything i used it was just to show lawlz what he probably should have done instead bassir;
A challenge: Do #79 on paper. I found it surprisingly easy. baddood;
Quote from: JMV on January 24, 2009, 06:52:29 PM
I didn't know you could do math in the print statement, but other than that it was close to what guff had.
That's the very first thing any python guide teaches you. goonish
Quote from: Pancake Persona on January 24, 2009, 10:56:04 PM
That's the very first thing any python guide teaches you. goonish
Well I guess me not reading any guides would be a factor. n_u
Quote from: Gladjaframpf on January 24, 2009, 10:27:59 PM
A challenge: Do #79 on paper. I found it surprisingly easy. baddood;
that actually does seem doable baddood;
i'll try it later maybe
also i think i'm going to try and do some of the problems i've already done in c akudood;
I did #79 in TextEdit only because I didn't want to waste paper.
[spoiler]73162890[/spoiler]
I had to register another account to test that so when I do it with actual code I won't feel like I cheated by submitting a problem with no programming. akudood;
Quote from: Pancake Persona on January 24, 2009, 11:23:55 PM
Solved 4:y = []
for i in range(100, 1000):
x = str(i*i)
if x == x[::-1]:
y.append(int(x))
print max(y)
Now I've just got to make a slimmer solution
uh that gives the wrong answer doodhuh;
you're assuming that the asnwer will be a perfect square (hint: it isn't) akudood;
Quote from: guff on January 25, 2009, 10:02:54 AM
uh that gives the wrong answer doodhuh;
you're assuming that the asnwer will be a perfect square (hint: it isn't) akudood;
I just ran that too and the answer is way off. doodhuh;
lol jmv beat lawlz n_u
Quote from: guff on January 25, 2009, 10:29:48 AM
lol jmv beat lawlz n_u
what was that
Quote from: Pancake Persona on January 21, 2009, 12:57:22 PM
I just wonder if JMV could actually do any of them
baddood; baddood; baddood; baddood;
Quote from: guff on January 25, 2009, 10:02:54 AM
uh that gives the wrong answer doodhuh;
you're assuming that the asnwer will be a perfect square (hint: it isn't) akudood;
oh goddamnit :'(
I'll work on the true solution
"""A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.
Find the largest palindrome made from the product of two 3-digit numbers."""
y = []
for i in range(100, 1000):
for o in range(100, 1000):
x = str(i*o)
if x == x[::-1]:
y.append(int(x))
print max(y)
That should be right... I hope.
But I really, really hate the way I did it and it's also really slow, so I'm going to rework it for a better solution.
Quote from: Pancake Persona on January 26, 2009, 12:05:22 AM
oh goddamnit :'(
I'll work on the true solution
You didn't check if you had the right answer before posting the code? akudood;
and yeah that one works.
QuoteJMV290
AIM
10:37
something is werid.
10:37
weird ;_;
Commodore Guff
AIM
10:37
how so
JMV290
AIM
10:37
/*Find the sum of all the multiples of 3 or 5 below 1000.*/
package euler_001;
/**
*
* @author jamesvalente
*/
public class Euler001 {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (3 % i == 0 || 5 % i == 0) {
sum += i;
}
}
System.out.println(sum);
}
}
10:37
That should work
10:38
but it gives me 9
10:38
solution someone gave for the problem after i gave up and looked
10:38
public class mathschallenge
{
public static void main(String[] args)
{
int total = 0;
for(int i = 1; i < 1000; i ++)
{
if(i % 3 == 0 || i % 5 == 0)
total += i;
}
System.out.println(total);
}
}
10:38
same code except variable names
10:39
and the braces on the if statement don't change anything, they just make it more readable
Commodore Guff
AIM
10:40
dur
10:40
jamie
10:40
you have a serious problem with ordering things
10:41
the problem is in your if statement
10:41
3%i is the remainder you get when dividing 3 by i
JMV290
AIM
10:41
oh i forgot perentsitis
Commodore Guff
AIM
10:41
that's not what you want
10:41
NO
JMV290
AIM
10:41
lol
Commodore Guff
AIM
10:41
THAT'S NOT THE ISSUE
10:41
jamie
10:41
i%3 and i%5 are what you want
10:41
not 3%i and 5%i
JMV290
AIM
10:42
oh shit DYSLEXIA
Commodore Guff
AIM
10:42
:|
JMV290
AIM
10:42
forget this ever hapend THIS IS WHAT HAPPENS WHEN I EAT NO FOOD FOR HOURS
Commodore Guff
AIM
10:43
i save all my im logs
JMV290
AIM
10:43
IT NEVER AHPPENED GUFF
n_u
I'm hungry :(
PHP
<?php /** Find the sum of all the multiples of 3 or 5 below 1000.*/
$sum = 0;
for($i=1;$i<1000;$i++){
if($i % 3 == 0 || $i % 5 == 0){
$sum+=$i;}}
echo $sum;
?>
Java
/*Find the sum of all the multiples of 3 or 5 below 1000.*/
package euler_001;
/* @author jamesvalente*/
public class Euler001 {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
System.out.println(sum);
}
}
Python
#!/usr/bin/python
# Filename : Euler_001.py
# Find the sum of all the multiples of 3 or 5 below 1000.
print sum(range(3, 1000, 3)) +sum(range(5, 1000, 5)) - sum(range(15, 1000, 15))
/* Problem 1:
Find the sum of all the multiples of 3 or 5 below 1000.
*/
#include <stdio.h>
int main() {
int sum = 0;
int i;
for(i = 0; i < 1000; i++) {
if((i % 3 == 0) || (i % 5 == 0)) {
sum += i;
}
}
printf("%d\n", sum);
return(0);
}
i hate c i hope it dies madood;
Quote from: guff on January 26, 2009, 09:39:47 AM
/* Problem 1:
Find the sum of all the multiples of 3 or 5 below 1000.
*/
#include <stdio.h>
int main() {
int sum = 0;
int i;
for(i = 0; i < 1000; i++) {
if((i % 3 == 0) || (i % 5 == 0)) {
sum += i;
}
}
printf("%d\n", sum);
return(0);
}
i hate c i hope it dies madood;
it looks like java.
speaking of java, brb removing multilne comments I don't need. akudood;
And, in Javascript. baddood;
<script type="text/javascript">
//Find the sum of all the multiples of 3 or 5 below 1000.
var sum=0;
for(var i=0;i<1000;i++){
if(i%3==0 || i%5==0){
sum+=i;
}
}
document.write(sum);
</script>
PLT Scheme:
(display (foldr + 0 (build-list 1000 (lambda (x) (if (or (= (modulo x 3) 0) (= (modulo x 5) 0)) x 0)))))
Displayed on one line for maximum unreadability. akudood;
MIPS Assembly:
lis $1
.word 0
lis $2
.word 1
lis $3
.word 1
lis $4
.word 3
lis $5
.word 5
lis $6
.word 1000
loop:
div $2, $4
mfhi $7
beq $7, $0, 3
div $2, $5
mfhi $7
bne $7, $0, 1
add $1, $1, $2
add $2, $2, $3
slt $7, $2, $6
bne $7, $0, loop
jr $31
This doesn't actually print the result, it just stores it in register $1, but I didn't want to stick the print routine in because it's big and ugly and my MIPS emulator automatically prints the contents of all the registers when it's done processing anyways.
I need to find out how to do loops in Clojure. madood; madood; madood;
whoa, i didn't even notice guff did number 1 in c
Because that's what I just did:#include <stdio.h>
main(){
int i, x;
i = 0;
x = 0;
while (i<1000){
if (i % 5 == 0 || i % 3 == 0)
x+=i;
i++;
}
printf("%d \n\n", x);
}
i kept getting the wrong answer with this for a good twenty minutes and it was driving me nuts and then finally asked jmv. the second i hit my return key, i noticed i forgot to define x goonish
sum [i|i<-[1..999],i`mod`3==0||i`mod`5==0]
haskell akudood;
i could probably shorten it a bit using the same trick i did for my python solution but this was easier to write in ten seconds because i didn't have to look anything up
+/((-.*5|>:i.1000) +. (-.*3|>:i.1000))#>:i.1000
j akudood;
i haven't looked at j for a while now and after seeing this code again i remember why
my code for this is horribly innefficient; ideally i should only have to call i.1000 once but using the stuff i knew this was the only way i could think of at the time baddood;
Quote from: guff on January 26, 2009, 02:39:00 PM
sum [i|i<-[1..999],i`mod`3==0||i`mod`5==0]
okay shortened it to:
sum [i|i<-[1..999],0`elem`[i`mod`3,i`mod`5]]
and by shorter i mean i made it a little longer but it would be shorter if shit damn haskell used shit damn % for modulo akudood;
okay did a ruby version too akudood;
total = 0
for i in 1...1000 do total += i if [i % 3, i % 5].include? 0 end
puts total
gosh i gave up on ruby a while ago for python but on using it again i love its syntax so very much
it just needs list comprehensions
i also realized i ended up writing a sum function because i don't think ruby has one built in:
module Sum
def sum
total = 0
for element in self do total += element end
total
end
end
class Array
include Sum
end
then i realized that my code didn't even use it but if it did it would have looked pretty n_u
okay jmv's supposedly been trying to learn clojure so i decided to try and make him look silly by solving problem one in it while having no idea how to do anything in it baddood;
((def sum 0)
(loop [i 0]
(when (< i 1000)
(if ((fn [x] (or (= 0 (rem x 3)) (= 0 (rem x 5)))) i) (def sum (+ sum i)))
(recur (inc i))))
(println sum))
it prints out the correct answer
but it also encounters some catastrophic errors or something at the end i dunno at least it gives the answer akudood;
granted all i had to go on was skimming through this (http://www.moxleystratton.com/article/clojure/for-non-lisp-programmers) small tutorial so i had no idea how to do, say foo += bar all lisp-like so instead i had to do (def foo (+ foo bar)) and i'm pretty sure there's got to be a better way
i should also probably try and figure out why the loop explodes but there really doesn't seem to be that many tutorials for clojure floating around akudood;
People who use looping constructs in functional languages go to SUPER HELL. akudood;
I don't know much about Clojure specifically, but since it's a Lisp dialect I'd recommend making a recursive function that takes a parameter n and counts down from n to zero. Then you can just call the function with 999.
Quote from: Gladjaframpf on January 27, 2009, 06:44:34 PM
People who use looping constructs in functional languages go to SUPER HELL. akudood;
I don't know much about Clojure specifically, but since it's a Lisp dialect I'd recommend making a recursive function that takes a parameter n and counts down from n to zero. Then you can just call the function with 999.
yeah probably but recall that this was hastily done in five minutes with no prior knowledge of clojure or any lisp for that matter baddood;
i'll just stick to haskell for my future functional programming needs screw you and your strict evaluation akudood;
Quote from: guff on January 27, 2009, 06:50:08 PM
yeah probably but recall that this was hastily done in five minutes with no prior knowledge of clojure or any lisp for that matter baddood;
i'll just stick to haskell for my future functional programming needs screw you and your strict evaluation akudood;
Yeah I looked at the tutorial you were working from and it sucked so I don't blame you. I guess since it's designed for non-Lisp programmers it's trying to demonstrate things that someone used to imperative languages would recognize, but that's kind of silly because the whole point of learning languages with different paradigms is to explore new ways of doing things.
okay after looking a little more into the language i was able to write this (also i didn't look at your scheme solution until after i posted this):
(println (reduce + (filter (fn [i] (or (= (rem i 3) 0) (= (rem i 5) 0))) (range 1000))))
happy now akudood;
if i am going to get into any lisp dialect i need an editor with automatic parentheses matching that isn't emacs or vim because i don't want a whole shit damn operating system akudood;
Yes that is much better.
I noticed something sort of odd when I was doing that problem. Simply looping through the numbers 1 to 999 should be faster than my solution, which first makes a list of the numbers and then adds them up so it has to go through all the numbers twice. However, tests show that my solution is faster. I guess the built-in functions for creating and folding lists are so heavily optimized that it makes up for it.
Yo dawg, I heard you like least common multiples.
#!/usr/bin/python
# Filename : Euler_005.py
#What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?
def gcd(a, b):
while b != 0:
t =b
b = a%b
a = t
return a
def lcm(a,b):
d = a*b/gcd(a,b)
return d
print lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(1,2),3),4),5),6),7),8),9),10),11),12),13),14),15),16),17),18),19),20)
is there a way to get it so I don't need 1000000000000000 LCMs?
Quote from: Jacques Michel Valente on January 29, 2009, 08:45:13 PM
print lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(lcm(1,2),3),4),5),6),7),8),9),10),11),12),13),14),15),16),17),18),19),20)
OH MY GOD akudood;
there's more than one way to do it
you could use the reduce function, which takes a function and an iterable object as input so you could just do something like:
reduce(lcm, range(1, 21))
or, you could just use a for loop like this:
current_lcm = 1
for i in range(1, 21):
current_lcm = lcm(current_lcm, i)
the for loop might be a better idea if you intend to learn python3.0 because they moved reduce from the builtins to the functools module akudood;
lol computer nerds
Quote from: Bassir on January 30, 2009, 10:03:25 AM
lol computer nerds
Can't copypaste these problems? akudood;
Quote from: Jacques Michel Valente on January 30, 2009, 11:57:55 AM
Can't copypaste these problems? akudood;
i don't know python :'(
but i after seeing their neat logo i may consider it
Quote from: Bassir on January 30, 2009, 12:52:35 PM
i don't know python :'(
it takes all of five minutes to learn baddood;
UNLESS YOU ARE JMV akudood;
Quote from: guff on January 30, 2009, 01:12:30 PM
it takes all of five minutes to learn baddood;
UNLESS YOU ARE JMV akudood;
then it takes java
Just decided to do problem 9:
for a in range(1, 1000):
for b in range(1, 1000):
c = ((a**2)+(b**2))**.5
if a+b+c == 1000:
print a*b*c
exit()
it's an ugly way of doing it, but i got it right the first try
and i threw exit in there so it'd quit as soon as it found the solution instead of going for that tenth of a second more to solve it a second time
A solution to 25: x = []
y, z = 0, 2
while len(x) < 2:
x.append(1)
y += 1
while len(x) < 10:
x.append((x[y-2])+(x[y-1]))
y+=1
z+=1
if len(x) > 5:
del x[0]
y -= 1
if len(str(x[4])) > 999:
break
print z
Last I checked, JMV only had 9 problems solved and I now have 10.x = []
y, z, i = 0, 2, 0
while len(x) < 2:
x.append(1)
y += 1
while len(x) < 6:
x.append((x[y-2])+(x[y-1]))
y+=1
z+=1
if x[y-1] %2 == 0: i+= x[y-1]
if len(x) > 5:
del x[0]
y -= 1
if x[4] > 4000000:
break
print i
And there's my hideous solution to 2.
hey those there fibonatchis numbers sure do show up a few times i reckon a feller such as yerself could write a function for them instead of resorting to while loops every cotton-pickin' time bassir;
also my solution for 24 is two lines long and takes ~0.06 seconds to run n_u
granted it can be solved by hand if you do the math but brute force is usually more fun
Quote from: Pancake Persona on February 18, 2009, 10:22:11 PM
Last I checked, JMV only had 9 problems solved and I now have 10.x = []
y, z, i = 0, 2, 0
while len(x) < 2:
x.append(1)
y += 1
while len(x) < 6:
x.append((x[y-2])+(x[y-1]))
y+=1
z+=1
if x[y-1] %2 == 0: i+= x[y-1]
if len(x) > 5:
del x[0]
y -= 1
if x[4] > 4000000:
break
print i
And there's my hideous solution to 2.
#!/usr/bin/python
# Filename : Euler_002.py
#Find the sum of all the even-valued terms in the sequence which do not exceed four million.
a,d,b = 0,0,1
while a <= 4000000:
c=a
a=b
b+=c
if a%2==0:
d+= a
print d
yeah i've got no idea what the hell lawlz is doing with his code
also god damn start using python3 already all of you akudood;
Quote from: guff on February 19, 2009, 07:09:18 AM
yeah i've got no idea what the hell lawlz is doing with his code
also god damn start using python3 already all of you akudood;
i needed to create a list of fibonacci numbers for something and was like 'hey i can just recycle this'
although i see lots of problems with it and it really is terrible goonish
And pygame doesn't support python 3.0, so I can't.
Quote from: Pancake Persona on February 19, 2009, 12:43:42 PM
i needed to create a list of fibonacci numbers for something and was like 'hey i can just recycle this'
although i see lots of problems with it and it really is terrible goonish
And pygame doesn't support python 3.0, so I can't.
uh yeah that's what modules and functions are for baddood;
uh yeah it is and it's extremely complicated and i'm still not sure what the hell is going on in it and why are there so many magic numbers in your code akudood;
well then pygame
SUCKS akudood;
Quote from: guff on February 19, 2009, 01:36:38 PM
uh yeah that's what modules and functions are for baddood;
uh yeah it is and it's extremely complicated and i'm still not sure what the hell is going on in it and why are there so many magic numbers in your code akudood;
well then pygame SUCKS akudood;
for some reason, the crazier my code is the more i like it
short "simple" stuff wracks my brain for some reason, and really crazy methods of doing everything come smoother to me for some reason.
but i can really say this part of my code was completely pointless and stupid because i could've just started the list i wanted with the other thing with [1, 1] instead of this slop:
while len(x) < 2:
x.append(1)
y += 1
goonish
My main problem in both writing and programming is I never review my work and I just go with what works the first time. I'm certain if I spent 30 more seconds doing things I could do everything better, but it's an impossible habit to break.
also pygame doesn't suck, it's just that it's updated like once every four score and seven years
and it's better than learning sepples
a very, very slow solution to 5i = 0
while True:
if i != 0 and i % 11 == 0 and i % 13 == 0 and i % 14 == 0 and i % 15 == 0 and i % 16 == 0 and i % 17 == 0 and i % 18 == 0 and i % 19 == 0:
print i
break
i += 20
I'm certain guff has a better way of doing it, because this takes 5.63 seconds to run :'(
Quote from: Pancake Persona on February 20, 2009, 02:23:33 PM
I'm certain guff has a better way of doing it, because this takes 5.63 seconds to run :'(
uh well yeah look up euclid's algorithm
it's an easy peasy and pretty quick way to compute the gcd of two numbers, from which the lcm is easily to computed
then, to compute the gcd or lcm of a list, since both functions are associative, all you have to do is call reduce() with the function and that list (in this case range(1,21)) as arguments
and although i generally avoid recursion if you're too lazy to actually read the article the gcd function can be implemented as a one-liner:
def gcd(a,b): return a if b==0 else gcd(b,a%b)
from there, you can write the lcm function as:
def lcm(a,b): return a*b//gcd(a,b)
the rest is left as an exercise to the stupid, incompetent reader akudood;
Problem 55:import time
total = 0
for starter in range(0, 10000):
x = starter + int(str(starter)[::-1])
if x != int(str(x)[::-1]):
for i in range(1, 49):
x += int(str(x)[::-1])
if x == int(str(x)[::-1]):
break
if i == 48 and x != int(str(x)[::-1]):
total += 1
print "Answer is %d. Solved in %.3f" %(total, time.clock())
.18 seconds to solve, so not too bad.
Not even 6000 people solved it yet, making me feel even better about it.
i already had 55 solved so i decided to go back and try and make my solution as short and obfuscated as possible a la lawlz except i did it on purpose:
lychrel = lambda n,i=1: False if (n+int(str(n)[::-1]))==int(str(n+int(str(n)[::-1]))[::-1]) else True if i >= 50 else lychrel(n+int(str(n)[::-1]), i+1)
print([lychrel(i) for i in range(10000)].count(True))
takes about 0.46 seconds baddood;
the solution i'm keeping for my records though is far more verbose and actually makes use of function definitions
also i could've done this in one line if python supported anonymous recursion but i don't think it does but i did learn that if you bind a name to a lambda you can recurse akudood;
Quote from: guff on February 21, 2009, 01:24:47 PM
takes about 0.46 seconds baddood;
so how fast is your
real solution or is mine better spam;
Quote from: Pancake Persona on February 21, 2009, 01:29:05 PM
so how fast is your real solution or is mine better spam;
~0.26 (~0.36 if i use the recursive lyrchel function that's commented out instead which i think is prettier) so yours is slightly faster but god damnit i actually use functions so i've got overhead from that:
def reverse_digits(n): return int(str(n)[::-1])
def is_palindrome(n): return n == reverse_digits(n)
#def lychrel(n, i=1):
# return False if is_palindrome(n + reverse_digits(n)) else True if i >= 50 else lychrel(n + reverse_digits(n), i+1)
def lychrel(n):
for i in range(1, 50):
n = n + reverse_digits(n)
if is_palindrome(n): return False
return True
if __name__ == '__main__':
from time import time
start = time()
print(len([True for i in range(10000) if lychrel(i)]), time() - start)
maps;
also open up an interpreter session and run:
from test import pystone
pystone.full()
for comparison
my machine gets 49224.4 pystones per second
Quote from: guff on February 21, 2009, 01:39:32 PM
~0.26 (~0.36 if i use the recursive lyrchel function that's commented out instead which i think is prettier) so yours is slightly faster but god damnit i actually use functions so i've got overhead from that:
def reverse_digits(n): return int(str(n)[::-1])
def is_palindrome(n): return n == reverse_digits(n)
#def lychrel(n, i=1):
# return False if is_palindrome(n + reverse_digits(n)) else True if i >= 50 else lychrel(n + reverse_digits(n), i+1)
def lychrel(n):
for i in range(1, 50):
n = n + reverse_digits(n)
if is_palindrome(n): return False
return True
if __name__ == '__main__':
from time import time
start = time()
print(len([True for i in range(10000) if lychrel(i)]), time() - start)
maps;
also open up an interpreter session and run:
from test import pystone
pystone.full()
for comparison
my machine gets 49224.4 pystones per second
>>> from test import pystone
>>> pystone.full()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'full'
maps;
also, functions don't really matter if i'm really only doing one little thing like this, and speed is more important
although i knew if i didn't make up some function to do something, you'd get grumpy but i was just like 'lol' spam;
Quote from: Pancake Persona on February 21, 2009, 01:44:37 PM
>>> from test import pystone
>>> pystone.full()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'full'
oh duh i'm an idiot it's pystone.main() not full()
Quote from: Pancake Persona on February 21, 2009, 01:44:37 PM
maps;
also, functions don't really matter if i'm really only doing one little thing like this, and speed is more important
although i knew if i didn't make up some function to do something, you'd get grumpy but i was just like 'lol' spam;
well it's just good practice akudood;
Quote from: guff on February 21, 2009, 01:47:46 PM
oh duh i'm an idiot it's pystone.main() not full()well it's just good practice akudood;
54945.1 pystones/second
and i just ran your solution and got like .201 s
Good practice doesn't necessarily mean good solutions. spam;
although i guess that's not something i should talk about maps;
>>> from test import pystone
>>> pystone.main()
Pystone(1.1) time for 50000 passes = 0.99
This machine benchmarks at 50505.1 pystones/second
>>>
AND AGAIN
>>> from test import pystone
>>> pystone.main()
Pystone(1.1) time for 50000 passes = 0.97
This machine benchmarks at 51546.4 pystones/second
>>>
#!/usr/bin/python
# Filename : Euler_055.py
#How many Lychrel numbers are there below ten-thousand?
numLy=0
def isPalindrome(n): return str(n) == str(n)[::-1]
def rev(n): return int(str(n)[::-1])
def lychrel(n):
for i in range(50):
n+=rev(n)
if isPalindrome(n):
return False
return True
for i in range(10000):
if lychrel(i):
numLy+=1
print "Number of lychrel numbers is %d."%(numLy)
#!/usr/bin/python
# Filename : Euler_009.py
#There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
#a<b<c && a**2 + b**2 = c**2
from time import time
start = time()
def equalsC(a,b,c):
if c**2 == (a**2 + b**2):
return True
def sizeCheck(a,b,c):
if a<b<c:
return True
def sumCheck(a,b,c):
if a+b+c==1000:
return True
for a in range(500):
for b in range(500):
c=1000-a-b
if equalsC(a,b,c) and sizeCheck(a,b,c) and sumCheck(a,b,c):
print a*b*c
print time() - start
exit()
#!/usr/bin/python
# Filename : Euler_008.py
#Find the greatest product of five consecutive digits in the 1000-digit number.
from time import time
start = time()
bigFuckingNumber="*number removed since it stretches the code box*"
prod = 0
for i in range(996):
dummy =int(bigFuckingNumber[i]) * int(bigFuckingNumber[i+1]) * int(bigFuckingNumber[i+2]) * int(bigFuckingNumber[i+3]) * int(bigFuckingNumber[i+4])
if dummy> prod:prod = dummy
print prod
print time() - start
#!/usr/bin/python
# Filename : Euler_013.py
# Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
file = open('files/13.txt')
lineList = []
for line in file:lineList.append(int(line))
print str(sum(lineList))[:10]
okay so is jim or lawlz winning now baddood;
solved problem 231, and my code runs in about 56 seconds akudood;
from euler_functions import sieve_of_erat
def factor_sum(factors_dict):
return sum(factor * exponent for factor, exponent in factors_dict.items())
def dict_add(dict_a, dict_b):
result_dict = {}
for key in set(dict_a.keys()) | set(dict_b.keys()):
result_dict[key] = dict_a.get(key, 0) + dict_b.get(key, 0)
return result_dict
def binomial_factors(n, k): # n!/(k!*(n-k)!) factorization = n! factors - k! factors - (n-k)! factors
primes = {n: sieve_of_erat(n), k: sieve_of_erat(k), n-k: sieve_of_erat(n-k)}
factors = {n: {}, k: {}, n-k: {}}
for number in (n, k, n - k):
for p in primes[number]:
p_count = 0
i = 1
while number // (p ** i) >= 1:
if number == n:
p_count += number // (p ** i)
else:
p_count -= number // (p ** i)
i += 1
factors[number][p] = p_count
return dict_add(factors[n], dict_add(factors[k], factors[n-k]))
doesn't include the code that actually generates the answer though just so no one gets tempted baddood;
after looking at the forum, there's many different ways of doing it some of which are faster and some of which are shorter but this is just what i came up with first baddood;
GUFF GET ONLINE HELP ;_;
I did 14 and it runs in about 13 seconds(down from 49) if I check only odd numbers and start at 500,001(sicnce all of the odds will return an even which then gets cut in half, and all of the evens above 500k will be at least 1 more than all the evens below it)
#!/usr/bin/python
# Filename : Euler_014.py
# Which starting number, under one million, produces the longest chain?
from time import time
start = time()
longestChain = 0
chainValue = 0
#Calculate and return the length of a chain
def chain(n):
lengthChain= 0
while n>1:
if n%2==0:
n/=2
else:
n= (3*n)+1
lengthChain+=1
return lengthChain
#Check up to 1 million.
for i in range(500001,1000000, 2):
if chain(i) > longestChain:
longestChain = chain(i)
chainValue=i
#Time to print shit
print chainValue
print chain(longestChain)
print time() - start
If I changed my function to def chain(n):
lengthChain= 0
while n>1:
if n%2:
n= (3*n)+1
else:
n/=2
lengthChain+=1
return lengthChain
It will run about one second faster, but it doesn't look as neat.
With Guffnigger's help I turned:
ValenteMac:Python jamesvalente$ python Euler_010.py
142913828922
29.1039888859
ValenteMac:Python jamesvalente$
into:
ValenteMac:Desktop jamesvalente$ python Euler_010.py
142913828922
3.5488049984
ValenteMac:Desktop jamesvalente$
Between 9 and 10 times faster. baddood;
Further optimization:
ValenteMac:Python jamesvalente$ python Euler_010.py
142913828922
2.34858393669
ValenteMac:Python jamesvalente$
I think Guff and I are the only people who post in this thread. baddood;
Quote from: Raekewn on February 26, 2009, 02:16:51 PM
I think Guff and I are the only people who post in this thread. baddood;
those nerds madood;
hy
Quote from: Ezlo on February 26, 2009, 02:51:29 PM
hy
what does this mean.
is it hi or or like how are you or what
QuoteCongratulations, the answer you gave to problem 46 is correct.
Nice work, Guff, you've just advanced another level.
baddood;
I REVIVE THIS THREAD. THE POWER OF GOD
#Find the sum of all the multiples of 3 or 5 below 1000.
sum=0
for i in (1..999)
if i%3==0 or i%5==0
sum+=i
end
end
puts sum
Problem 1 in Ruby.
Quote from: ra-ˈkün on April 10, 2009, 10:35:41 AM
I REVIVE THIS THREAD. THE POWER OF GOD
#Find the sum of all the multiples of 3 or 5 below 1000.
sum=0
for i in (1..999)
if i%3==0 or i%5==0
sum+=i
end
end
puts sum
Problem 1 in Ruby.
already done punk akudood;
you're the punk