Need help for Cody Problem 42409: Divisible by 7

2 views (last 30 days)
Hi! I am new in Matlab programing. I try to learn this language through cody problem. But I couldn't solve this problem for a long time. It'll be a great help for me if you give me some solutions!
I have been trying this problem to solve for a several time but everytime it shows the same error. When I run this code in the Scratch Pad, I get the desirable result, but when i submit my code, it shows an error: "The server timed out while running and assessing your solution. Use the Run button to verify your code. If successful, submit again.If the error persists, contact the instructor.".
**For your information, in this problem I can not use direct functions to get the answer. I have to do everything manually. Please see the problem question first in the link below.
I am submitting my written code here and also the link of the Cody Probelm. Thanks in advance for your suggesitions!
x = num2str(n_str) - '0';
seven = [0 7 14 21 28 35 42 49 56 63 70 77 84 91 98];
l = length(x);
if l > 2
while l > 2
p = x(1:end-1);
p = num2str(p);
p(p == ' ') = [];
p = str2num(p);
s = p - x(end)*2;
x = num2str(s) - '0';
l = length(x);
s = str2num(n_str);
if any(seven(:) == s) == 1
tf = 1
tf = 0
Please tell me if there is anything wrong in my code or the arrangements.

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 4 May 2021
You are getting the error because your code took to long to process than the allowed time limit.
1 - The input is in the form of string so, use x = n_str-'0';
2 - You can get rid of the first set of if/else statements, and just use the while loop. Your code will work the same.
3 - You can improve the speed of your while loop by substituting statements which do the work quickly.
while length(x) > 2 %Instead of defining 'l' as a variable, directly use length(x).
p = polyval(x(1:end-1),10);
s = p - x(end)*2;
x = num2str(s) - '0';
%defining variable takes memory to be stored and needs memory to be calculated at every loop iteration
If you want to learn MATLAB, Cody is not the best place to do so. Cody is meant for practicing/applying the skills you learnt. I would suggest you start with MATLAB Onramp course.
Nafees Ul Haque Akhand
Nafees Ul Haque Akhand on 4 May 2021
Sure, I will try some other methods. Thanks for your help and sure will take the Onramp course you suggested.

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!