A Harshad number is one that is divisible by the sum of its digits. Write a Matlab program that prints out a list of all such three digit numbers and counts how many of these there are. How might you check that your program is working by using Excel?
The above is my question but i dont know how to create a code to add digits in numbers together for example, if i have the number 125 then i want to add up 1 + 2 + 5 but i have no idea of how to create the code for that part. i can do the rest i think

댓글 수: 4

John D'Errico
John D'Errico 2011년 2월 7일
But why should we do the hard part of your homework assignment?
Bhavik
Bhavik 2011년 2월 7일
but i've really tried doing it, done alot of research and i was led onto this wesbite. im not asking you to do my work, just want some guidance, tip, hint etc
Walter Roberson
Walter Roberson 2011년 2월 7일
You asked how to add the digits. Did you try the response I gave? If so, then did you have a problem with it for the purpose of adding digits? If not, then you have developed some code already and are seeing an error in your code, so post that current code.
Bhavik
Bhavik 2011년 2월 7일
i did something similar to your response and it works perfectly now. Thank you :D

댓글을 달려면 로그인하십시오.

답변 (4개)

Jan
Jan 2011년 2월 7일

1 개 추천

Hint:
log10(125)
rem(125, 10)
rem(125, 100)
Good luck
Walter Roberson
Walter Roberson 2011년 2월 7일

0 개 추천

T = num2str(n); S = -144; for K = 1:3; S = S + T(K); end;
By the way, the entire homework problem has a one-line completely-vectorized solution (without even arrayfun), and can be completely parameterized down to a single variable that represents the number of digits. For example, the solution for 2 digits is
10 12 18 20 21 24 27 30 36 40 42 45 48 50 54 60 63 70 72 80 81 84 90
Vieniava
Vieniava 2011년 2월 7일

0 개 추천

Analyze this solution:
N='435'; % number in a string format
S=sum(N-'0')-numel(N)*('0'-0);
Edit: Good point, Walter Roberson.
N='435';
S=sum(N)-numel(N)*'0'

댓글 수: 1

Walter Roberson
Walter Roberson 2011년 2월 8일
The -0 are not needed:
S = sum(N) - numel(N)*'0';
Beware of using numel when you go to vectorize this code.

댓글을 달려면 로그인하십시오.

Niranjan Borah
Niranjan Borah 2020년 10월 23일
편집: Walter Roberson 2020년 10월 23일

0 개 추천

Try this method. (link) ( https://didiknowthis.blogspot.com/2020/10/how-to-add-all-digits-in-number-in.html ). This shows how to do this thing even for a large number. For large number simple methods do not work.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

태그

질문:

2011년 2월 7일

편집:

2020년 10월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by