Effacer les filtres
Effacer les filtres

Generating a rather intricate loop with inequalities

2 vues (au cours des 30 derniers jours)
Sergio
Sergio le 18 Jan 2024
Commenté : Sergio le 18 Jan 2024
I have to create a code that, given positive integers m and n, calculates integers k and r such that m=kn+r and r<n by successively subtracting n first from m and then from m-n and then from m-2n and so on in a loop. as many times as possible without the remainder r=m-kn becoming negative, and which finally prints k and r on the screen.
This seems a little confusing, since r and k are not calculated readily, since we have an inequality at r<n, and not an equality. If it was r=n, we would have no problem and could proceed to the loop.
My code is as given, however, it stops since r<n and cannot be calculated. Any ideas how to solve this? Thanks
m=1
n=2
% Initialize the starting number
number = m;
% Loop
while number <= m-n*n
disp(number);
number = number-n; % Subtract n from m
end
if r==m-kn;
end
if r<n;
end

Réponse acceptée

Hassaan
Hassaan le 18 Jan 2024
Modifié(e) : Hassaan le 18 Jan 2024
Your current code does not correctly calculate k and r. Here's an adjusted version:
m = 1; % Example values for m
n = 2; % Example values for n
% Initialize k and r
k = 0;
r = m;
% Loop to find k and r
while r >= n
r = r - n; % Subtract n from r
k = k + 1; % Increase k by 1 for each subtraction
end
% Display the results
fprintf('k: %d, r: %d\n', k, r);
k: 0, r: 1
This code initializes k and r, then uses a loop to subtract n from r until r is less than n. Each subtraction increases k by 1. After the loop, k and r will satisfy the conditions m = kn + r and r < n.
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Feel free to contact me.
  1 commentaire
Sergio
Sergio le 18 Jan 2024
Thanks Muhammad, but why did you set k=0?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits


Version

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by