Generating a rather intricate loop with inequalities

4 ビュー (過去 30 日間)
Sergio
Sergio 2024 年 1 月 18 日
コメント済み: Sergio 2024 年 1 月 18 日
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

採用された回答

Hassaan
Hassaan 2024 年 1 月 18 日
編集済み: Hassaan 2024 年 1 月 18 日
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 件のコメント
Sergio
Sergio 2024 年 1 月 18 日
Thanks Muhammad, but why did you set k=0?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by