using mod function for checking integers

10 Ansichten (letzte 30 Tage)
Jacob Kolterjahn
Jacob Kolterjahn am 6 Mär. 2018
Kommentiert: serdar am 4 Jun. 2020
I have a short assignment for a MATLAB class and I am in need of a quick refresher and some help. SO The question states that i need to make an Array from 1 to 1000 and divide each of those numbers by an array of the prime numbers 2,3,5,7,11,13,17,23. and if the number in the first array is divisible by the prime number you add 1 to a final array for that prime number. I know what the code should do but not sure how to check if it is divisable by the prime number.
clear clc K = (1:1000) primenum = (2,3,5,7,11,13,17,23) divisable_by_prime = (A,B,C,D,E,F,G,H) if ( part im not sure about) %IF K/2 is an integer A= A+1 else if ( part im not sure about) %IF K/3 is an integer B= B+1 ... so on and so forth. I think you have to use the mod function but i'm not sure how to. any help would be appreciated!

Akzeptierte Antwort

John D'Errico
John D'Errico am 6 Mär. 2018
Why not play with mod? See what it does? Lets see what we can do.
K = 1:10;
Now, pick some number that we want to use to test for divisibility.
p = 3;
So, which elements of K will P divide exactly? We would expect 3, 6, and 9 for this vector of integers K and divisor P. So if you understand how mod works, what does this tell you?
mod(K,p)
ans =
1 2 0 1 2 0 1 2 0 1
find(mod(K,p) == 0)
ans =
3 6 9
So when mod(K,p) is zero, that tells us that p divides K, or the corresponding element thereof for vector K.
Similarly, does 17 divide 34?
mod(34,17)
ans =
0
Yes, it does. But not 35.
mod(35,17)
ans =
1
As far as your assignment goes, you need to spend some time working it out. But this should get you started.
  1 Kommentar
serdar
serdar am 4 Jun. 2020
Thank you for you answer on the behalf of person who asked the question.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by