r/shittyprogramming • u/FritangadeLuka420 • Sep 14 '18
Beginning in C++
I'm working in a small homework and the last step is calculate the least common multiple but with easy steps like if or something like that, could someone help me?
14
Upvotes
54
u/zone_31 Sep 14 '18
Hardcode it with a switch statement. The compiler will make it into a jump table, making it crazy fast!
7
u/[deleted] Sep 14 '18
std::lcm in <numeric>
If you don’t want to use the standard library, then you can’t do it with if statements only.
7
u/bolche17 Sep 14 '18
Bruteforcing it is always a option. Just do a for that loops through all the numbers until the product of the denominators and break it if you find a number divisible by both
33
u/[deleted] Sep 14 '18
shittyprogramming hat removed
If you actually want help, you should probably go to a different subreddit. This one is kind of a joke subreddit about really, really bad code. I would suggest posting the exact wording (a snippet of an assignment copy-pasted if possible) and then maybe people can help you. But I would do it on /r/learnprogramming or something, this isn't the right place.
shittyprogramming hat unremoved
Precalculating is your friend.
Before you know it, you'll have what we software engineers like to call a look up table!
18
u/scooty14 Sep 14 '18 edited Sep 15 '18
Least common multiple of numbers A and B is A*B divided by greatest common divisor of these numbers.
Now you need to calculate greatest common divisor, should be pretty easy:
lcm(a,b) = (a*b) / gcd(a,b) ... *gcd(a,b)
gcd(a,b) * lcm(a,b) = a * b ... /lcm(a,b)
gcd(a,b) = (a*b) / lcm(a,b)
Lets write the function:
With both functions defined, you can just call your function:
this will print 12
11
u/dmitriy_shmilo Sep 14 '18
16 hours later and not a single one of you suggested machine learning? Shame on you, ML is just a bunch of
ifs in a black box that's literally what OP needs.1
u/napoleoncalifornia Sep 14 '18
lambda : 3
1
u/jplank1983 Sep 14 '18
I was staring at the post and trying to find the joke for way too long.