A combination of coins to give as close or exact as possible to 200 grams

Joined
Mar 17, 2025
Messages
1
Reaction score
0
Where did I go wrong? The goal is to find the number and combination of coins weighing 5.78 grams, 5.05 grams and 4.2 grams to give as close as possible or exactly 200 grams. It is QBASIC. Is there such a thing on the internet?

Code:
din = 0
pet = 0
dva = 0


aktuelno = 250



for a = 0 to 48
pet = din

for b = 0 to 41 - a
pet = dva + din


for c = 1 to 36 - b - a

pet = pet + 5.78
tekuce = ABS(200 - pet)

if tekuce < aktuelno
   aktuelno = tekuce
   pamtimdin = a
   pamtimdva = b
   pamtimpet = c
end if

next c
dva = dva + 5.05

next b
dinar = dinar + 4.2

next a


print aktuelno

print "pet: " ; pamtimpet
print "dva: " ; pamtimdva
print "din: " ; pamtimdin
 
Last edited:
Joined
Sep 20, 2022
Messages
230
Reaction score
38
All 3 loops can go from 0 to 50, because you're using a brute force method. Extra iterations won't hurt, and it keeps things simple.
Code:
aktuelno = 201
for a = 0 to 50
  for b = 0 to 50
    for c = 0 to 50
      pet = 4.2*a + 5.05*b + 5.78*c
      tekuce = ABS(200 - pet)
      if tekuce < aktuelno
        aktuelno = tekuce
        pamtimdin = a
        pamtimdva = b
        pamtimpet = c
      end if
    next c
  next b
next a
print aktuelno
print "pet: " ; pamtimpet
print "dva: " ; pamtimdva
print "din: " ; pamtimdin
The inner loop can be removed, c can be calculated directly from a and b. It's a bit messy.
Code:
for a = 0 to FLOOR(200/4.2)
  for b = 0 to FLOOR((200 - 4.2*a)/5.05)
    c = (200 - 4.2*a - 5.05*b)/5.78
    c = FLOOR(c + 0.5)
    ...
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,260
Messages
2,571,039
Members
48,768
Latest member
first4landlord

Latest Threads

Top