creating function to find odd numbers upto 10000 having sum of its digits an odd number itself( e.g. 29)

4 views (last 30 days)
if n%2==0
number is even
else
number is odd
end

Answers (1)

David Fletcher
David Fletcher on 1 Apr 2018
%Create list of odd numbers as cell array of character vectors
oddNum_str=regexp(num2str(1:2:10000),'\d+','match');
result=[];
for iter=1:length(oddNum_str)
%index number and turn characters back to separate numbers
digits=int32(oddNum_str{iter})-48;
if mod(sum(digits),2)==1
%Quick and dirty record of odd numbers with odd sum
result=[result str2num(oddNum_str{iter})];
end
end
I am unsure if this is a homework question, though it looks suspiciously like it. If it is indeed homework, I strongly advise that you don't just turn this into a function and present it as your solution, as I suspect your tutors will be somewhat doubtful that it came from you. You can improve on it however - this is a brute force search in that it checks all odd numbers between 1 and your upper limit. Have a look at the results produced by this and see if you notice a pattern - it may inspire you to do something better (or at least something different)
  1 Comment
John D'Errico
John D'Errico on 12 May 2018
Can you seriously think of a case where someone would want to do this for their own work, and not as homework? If you want to help them, guide them to think about how to solve the problem, but not provide a solution.

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!