MATLAB: Using mod function for checking integers

divsionintegersmod

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!

Best Answer

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.