Project Euler, problem 5

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

This one needed some rambling thought before I settled down to an approach. I had thought that there should be a more effective method than simply counting upwards while testing each number in the range.

I settled on the simple approach when I realised that when checking the current highest number, you can skip all remaining items in the range should there be a single failure to evenly divide.

My brief, if inelegant solution – which I’ll hopefully refine in the next few days – is copied below (written in Ruby). I can’t help but think there are ways to:

  • cut down the number of division checks
  • increment the high number by greater degrees each time

So plenty still to examine with this one.

$greatestNumber = 1
def checkHigh()
  rangeLow = 1
  rangeHigh = 20
  i =  rangeHigh  
  singleNumbersNonRemainDivCount = 0
  while i >= rangeLow
    if ($greatestNumber % i)   > 0
        singleNumbersNonRemainDivCount=0
        $greatestNumber = $greatestNumber+1    
        i = rangeHigh      
    else
        singleNumbersNonRemainDivCount=singleNumbersNonRemainDivCount+1
        if singleNumbersNonRemainDivCount == rangeHigh
          puts "Highest number: #{$greatestNumber}"
          $greatestNumber   = $greatestNumber-1
        end
        i=i-1
    end
  end
end
checkHigh()

Only 344 days to go

Here’s the crop of self-portraits from the last week:

January 16th:

A frustrating start to the week – a small oil study that I had to abandon. I took a rag to the wet surface in the hope of resurrecting it at some point.

January 17th:

I returned to pencil & cartridge paper, looking at the shots I took of this showed me I need to watch my shading – I did some corrections before uploading the day’s final image.

January 18th:

Light blue letraset marker on watercolour paper, stood very close to the mirror.

January 19th:

Heavily sleep deprived in this one, so no smiles. Enjoyed the differences made by holding my head – fold’s around the eyes and more interesting shadows.

January 20th:

A quick follow up of the same themes on the next night – having had some sleep. Again some tonal adjustments made with an eraser before finalising.

January 21st:

A total departure – animal transformation for a start, and my first linocut print in more years than I care to recall.

Linocut is very rewarding – the design was drawn up in a sketchbook and applied in pencil then ink, but was being adapted during the cutting process. Cutting took about an hour to complete. I had hoped printing would have been more successful, so I’ll be working on the home pressing techniques.

January 222nd:

After last night’s lino print, I’d tried to get a monoprint from the remaining ink on the glass but was unsucessful. I rolled the ink evenly again and left it to dry so that today I could scratch into it directly and then backlight it, here’s the result of some swift scratching.

media

I’ve thought alot about media this week – particularly grounds and supports – with an anything-goes mindset.

I’ve tried painting on a (spare, unused) smoke alarm (pencil works well, but using an eraser was surprisingly problematic given the plastic surface) and I’m now considering what can be achieved with other materials as either a support or a sculptural / relief material.

Expect noodles.

How it’s going

I’ve been tempted this week to adapt (at best) or abandon the whole project – mainly because it’s already provided me with the intended results – I’m working creatively, regularly and in range of media.

I now have a list of painting, printing and other works I want to begin, so producing a daily portrait can seem like a burden.

Perhaps ‘one self-portrait a fortnight’ will be the way to go? For now I’m going to persevere. I’ve proved I can make the time so I’ll try to get some longer-term projects running in parallel.

Project Euler problem 8

The latest in a series of paired-up problem workings with Greg Bowie. This week we’re looking at Problem 8:

Discover the largest product of five consecutive digits in a the [provided] 1000-digit number

Here’s my response, longhand:

  1. I’ll need a variable to store the (current) value of the greatest product
  2. I’ll need to iterate through the 1000-digit number, reading 5 digits at a time working out the product of each sequence, stepping one digit on with every iteration.
  3. The routine will begin from the 1st digit. The process will stop 5 digits of the final digit
  4. Using variables to store the length of the 1000-digit number and the number of digits we’re deriving the product of would make the solution more adaptable for other numbers and sequences
  5. Each product retrieved from every sequence of 5 digits must be compared to the current greatest product. If this exceeds the current greatest product, we set this as the new greatest product

This should solve the problem, but why stop now?

Refinements

The presence of zeros in the 1000-digit number is notable – any zero encountered while examining the product of multiple digits will result in a zero product. So I’ll ignore them:

  1. Create an array of smaller numbers by splitting the 1000-digit number by any zero digit – handling sequences of zeros so as to prevent empty array items
  2. Iterate through each of these numbers, deriving the product of each set of 5 digits, and checking this against the current greatest product

Chances are this refinement will not improve the performance of this test on a single number, but as it reduces the number of product-derivation runs by 398 by it may scale well, depending on the language.

ratherLongNumber = 73167176531330624919225...
numDigits = ratherLongNumber.to_s.length
considerRange = 5
totalcomparisons = 0
$greatestProduct = 0
while totalcomparisons range = ratherLongNumber.to_s[totalcomparisons,5]
rangeproduct = range.split(//).map(&:to_i).inject(:*)
$greatestProduct = $greatestProduct>rangeproduct ? $greatestProduct:rangeproduct
totalcomparisons=totalcomparisons+1
end
puts "#{$greatestProduct}"

Refined version:

ratherLongNumber = 73167176531330624919225...
def getProductOfRange(inputNumber,considerRange)
# puts inputNumber
numberofcomparisons = 0
localGreatestRange = 0
while numberofcomparisons range = inputNumber.to_s[numberofcomparisons,5]
rangeproduct = range.split(//).map(&:to_i).inject(:*)
numberofcomparisons=numberofcomparisons+1
localGreatestRange = localGreatestRange>rangeproduct ? localGreatestRange:rangeproduct
end
return localGreatestRange ,numberofcomparisons
end
$greatestProduct = 0
arrayOfNumbers = ratherLongNumber.to_s.split(/0+/).map(&:to_i)
arrayOfNumbers.each{
|a|
tmp2,comparisons = getProductOfRange(a,5)
$greatestProduct = $greatestProduct>tmp2 ? $greatestProduct:tmp2
}
puts "#{$greatestProduct}"

here’s Greg’s response, posted simultaneously today.

update 23/01/2012:

Revisiting this afresh I realise there’re other ways to skip those pesky zeros, rather than drop them into an array, better to simply skip past any such sequence:

ratherLongNumber = 73167176531330624919225...
numDigits = ratherLongNumber.to_s.length
considerRange = 5
greatestProduct = 0
cursor = 0
skipped = 0
while cursor <= numDigits-considerRange
range = ratherLongNumber.to_s[cursor,considerRange]
if range.index('0')
cursor=(cursor+range.index('0'))+1
skipped=skipped+1
else
rangeproduct = range.split(//).map(&:to_i).inject(:*)
greatestProduct = greatestProduct>rangeproduct ? greatestProduct:rangeproduct
cursor=cursor+1
end
end
puts "Greatest Product: #{greatestProduct}"
puts "#{skipped} sequences with zero in the #{considerRange}-digit range skipped"

A second week of self

Week two: surreal, desperate, but going in the right direction.

At the start of the week I found I could get a likeness without looking, just idly doodling in sketchbook. This is bad news, it’s the process of observation that’s important, not the ability to recall. So I’ve tried to take more time over the plain, representational ones this week.

I’ve thrown in some other approaches too – depicting my face upon a small matryoshka doll stood upon a notebook (‘that’s rather sinister’ was one response), and another looking out over the river but will odd, converging shadows.

I am still not producing the kind of work I would like to, but the journey’s begun and most importantly I’m thinking far more, and further ahead.

Available time remains a big factor. Thankfully at the weekend I had some time to run through various ideas and use some other media.

One Self-Portrait a day

At 6am on January the first, I sketched a self-portrait:

…it's too early for this!

…and thought that might be a fun, creative, enlightening, educative and perhaps exasperating thing to do every day.

Every day of 2012 I’ll execute a self-portrait, and share it using Twitter the same day. Sharing them provides an impetus to complete each day’s portrait, and gives me the determination to work on my methods and my approach.

An audience (even a theoretical one) gives me a reason to improve. The risk is that you end up sharing 365 crap images of yourself with the world, the pay-off is that every day you add to your experience, your conceptual and technical capabilities, and your satisfaction with your work.

Week one’s self-portraits

The output so far has been representational, brief and sketchy, possibly no surprise at the outset. Representationally, they’re not up to much. I am capable of better, but this is a journey.

Time

The greatest constraint so far has been time. Time to conceive an approach to a portrait as well as time to execute it. Thus the first week’s output has been low concept, and quickly executed. I’ve tried to vary media a little during the week but each has been a very direct method.

Not having the time to work on drawing and painting is the best reason I can think of to continue this project, regardless of the work produced.

Concept

Telling yourself you have to do this, every day, is at once a burden and a joy. Until you place constraints on what you do, you don’t realise the clarity of thought you can attain within those limits.

I have many plans for where this project will take me, my thought processes and my experience with various media. My immediate aims are to work in paint and some form of printing as soon as I can, but working with traditional media will just be one part of the project.

Every week or so, I’ll add a post here on recent works and where I think they’re heading, and more importantly where they’re taking me.

 

Inaugural Preston CodeJo, November 28th 2011

Facilitated by @ruby_gem and hosted by @phpcodemonkey, the first Preston CodeJo was held last night at Magma Digital’s offices on Winckley Square. Using themed ‘katas’, this is the first of an open-ended series of events designed to challenge and extend developer abilities and interaction across programming/development disciplines.

This month’s kata asked attendees to use a Test-Driven Development (TDD) approach to solving a simple problem using the Ruby language.

Continue reading

Final thoughts on PHP North West 2011

PHP NW 2011 informationSunday’s track choices

My second day at the PHP North West Conference 2011 kicked off with Paul Lemon’s ‘Feeling Secure?’ talk.

Paul used succinct code samples and made a point of covering the basic attack methods, assuming no great depth of knowledge for some and the need to re-iterate its importance to the rest of us. For each attack type, variant methods were demonstrated that perhaps would have been unfamiliar to some – this was certainly borne out during the Q&A session. Paul had far more topics to cover and hopefully there’ll be an extended security presentation at a future conference.

Following this I attended Walter Ebert‘s talk on URL design. Walter had gone to some trouble to locate examples of good practice in human-readable, RESTful web addressing as well as some neat workarounds for common problems – for example url handling routines for those long descriptive links that email clients break when they wrap text.

Finally I listened to Richard Backhouse talk about compiling PHP to .NET using open source tool Phalanger. Richard covered the background to his company’s adoption of the approach, client considerations, use cases and opportunities for mixing languages & libraries for a best-of-both approach.

Take Away

I tend to take away both strong themes and important (though sometimes small) messages from conferences that stick with me, influencing the design decisions and production routes on current and future projects. They’re not always from a favourite or most enjoyable presentation, but they highlight the event’s greater whole.

Laura Beth Denker‘s Saturday track 1 talk emphasised the need to retain practicality and perspective in software production (in particular, testing). Yes we have the tools, but are we using them effectively, are we curtailing our own faculties in favour automated methods, do we put enough trust in our collaborators?

The major frameworks has a strong showing, but Alistair Stead and Paul Lemon provided timely reminders of those areas that still require careful thought and action – response times, the right caching techniques regardless of chosen technology, the importance of validation and knoweldge of protocols and security basics.

Finally, Ian Barber‘s keynote brings all this together – the tools exist to allow you to contribute to great developments and create new ones. Use the right tools for right purpose and keep a keen eye on what’s around you – in programming, and in the wider world.

PHPNW11 was all about (as @Elblinkin put it) ‘Keyboard, mouse and You’.

Saturday at PHP North West 2011

The PHP North West conference gets bigger and better every year, and 2011 sees the Saturday and Sunday conference enlived by a Friday tutorial day and an unconference running alongside the scheduled tracks.

Saturday morning kicked off with keynote speaker Ian Barber‘s revealing tour of the small steps that made great software even better, and the ways that diverse personal interests, hobbies and a willingness to ignore conventional wisdom led to innovations that we in turn can build upon and contribute to.
Having a broad range of work and hobby interests, I could only agree with Ian on his belief in cross-fertilisation of ideas and approaches, and it was good to be reminded that being interested and aware is often more effective than aiming high.

Starting off Track 1, Enrico Zimuel introduced the new features and architecture of Zend Framework 2 followed by Sebastian Bergmann‘s talk on PHP Testing tools. Sebastian compared the various approaches and features of the most ubiquitous and newly released tools including his own project PHPUnit , the Atoum framework and the behaviour / scenario driven BeHat.

In the afternoon I attended Alistair Stead‘s track 2 talk about the Varnish reverse proxy cache. In addition to presenting Varnish’s impressive capabilities, Alistair examined the pitfalls of adding multiple cache layers, configuration gotchas, as well as privacy and security concerns in good depth.

Track 2 continued with Stefan Koopmanschap‘s introduction to the recently released Symfony2 framework. For those of us with experience of prior releases, Symfony2 appears to differ significantly and will take some getting used to. The Bundles approach follows the components theme running through the conference this year.

The final talk in track 1 was Laura Beth Denker‘s ‘Are your tests really helping?’. After informing the crowd that her company pushed code every 20 minutes or so, you would have expected a breakdown of intensive automated test routines, but what was presented was a practical approach involving well organised unit testing; having faith in fellow developers and trust in the external services (and if you don’t have faith or trust, you should probably replace both) in order to reduce the need for extensive integration and functional testing.

PHPNW11 continues today, Sunday 9th October. Feedback for talks can be read and provided on JoindIn.