programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Project Euler # 5

Greenhorn
Posts: 1
Down below I have a piece of code written for question five of project Euler:
What is the lowest common multiple of all the numbers between 1 and 20 (inclusive)?
I barely know any Java so I try to put up with what I know. When I try running this piece of code, nothing displays.

What should I change?

Saloon Keeper
Posts: 3330
46
A brute force approach would be to have an outer loop starting starting at 20 and going up, and to have an inner loop that counts from 2 to 20 inclusive. If the outer loop value is not evenly divisible by any inner loop value then break out of the inner loop. If then inner loop goes all the way through then you've found your answer.

While this will work conceptually I think you'll find that Euler's site will say it took too long, but I'd start with this anyway.

Sheriff
Posts: 22846
43
I'd start with a pencil and paper and a simpler problem. What's the LCM of the integers between 1 and 3 inclusive? (Your answer should be 6 -- if it isn't then review the definition of LCM.)

Once you've done that little calculation, ask yourself how you did it. Now what's the LCM of the integers between 1 and 4? Did you do that the same way?

After you do two or three iterations of this, you should have a reasonable idea of how you solved each of the simple problems, and you should be able to describe how to find the LCM of the integers between 1 and N. Don't worry that your Java experience isn't so good, write down in words how to do it. Once you've done that, try to convert the words into Java code.

I haven't addressed the code you wrote because it's just wrong. You can't get to the right answer by fiddling with that code, that's why I answered the way I did.

Paul Clapham
Sheriff
Posts: 22846
43
And, welcome to the Ranch!

Marshal
Posts: 56608
172
Welcome to the Ranch

When I was about twelve, I was taught the correct way to calculate an LCM was to use prime factors. Do you know how to get prime factors out of an integer?

 Don't get me started about those stupid light bulbs.