Matlab Prime number list checker - matlab

Ok so I have been having a go at creating a prime number checker. I have been successful in making it work for a specific number. The code is here.
#To test if number is prime
prompt = input("number to test if prime: ");
n = prompt;
i = 2; #start of mod test
t = floor(sqrt(n));
counter = 0;
tic
for i = 2:t
if mod(n,i) == 0
disp('n is not prime')
break
else
counter = (counter + 1);
end
end
if counter == t-1
disp('n is prime')
end
toc
I then tried to make a program which would test a range of numbers. It's been successful for n=10, but when I go higher than that it doesn't seem to pick up the primes. I'm not sure where I'm going wrong.
#Want to test numbers 2:n if they're prime
prompt = input("max number to test: ");
n = prompt;
l = 2; #start of mod test
counter = 0;
tic
for i = 2:n #cycle to test 2 up to n
t = floor(sqrt(i)) #Only need to test up to root of number
for l = 2:t
if mod(i,l) == 0
break
else
counter = (counter + 1);
end
end
if counter == t-1 # if tested up to the root of the number, it must be prime
prime = sprintf('%d is prime', round(i));
disp(prime)
counter = 0;
end
end
toc
Any help in getting it to work for larger values would be greatly appreciated and also any ways to make the code more efficient. The top program can test 982451653 in 0.268 seconds on my laptop.

Just a way to linearize your algorithm:
n = 997 %test number
t1 = n./([2,3:2:n/2]);
t2 = t1 - round(t1);
res = sum(t2 == 0); %can n be divided ?
if res == 0
fprintf('%s','prime');
else
fprintf('%s','not prime');
end

I got help on the issue and found that 'counter' was constantly re-setting and needed to be moved up. Fixed code is here
#Want to test numbers 2:n if they're prime
prompt = input("max number to test: ");
n = prompt;
l = 2; #start of mod test
counter = 0;
tic
for i = 2:n #cycle to test 2 up to n
t = floor(sqrt(i)); #Only need to test up to root of number
counter = 0;
for l = 2:t
if mod(i,l) == 0
break
else
counter = (counter + 1);
end
end
if counter == t-1; # if tested up to the root of the number, it must be prime
prime = sprintf('%d is prime', round(i));
disp(prime)
end
end
toc

Related

Output 1, 0.5, or 0 depending if a matrix elements are prime, 1, or neither

I am sending a matrix to my function modifikuj, where I want to replace the elements of the matrix with:
1 if element is a prime number
0 if element is a composite number
0.5 if element is 1
I dont understand why it is not working. I just started with MATLAB, and I created this function:
function B = modifikuj(A)
[n,m] = size(A);
for i = 1:n
for j = 1:m
prost=1;
if (A(i,j) == 1)
A(i,j) = 0.5;
else
for k = 2:(A(i,j))
if(mod(A(i,j),k) == 0)
prost=0;
end
end
if(prost==1)
A(i,j)=1;
else
A(i,j)=0;
end
end
end
end
With
A = [1,2;3,4];
D = modifikuj(A);
D should be:
D=[0.5, 1; 1 0];
In MATLAB you'll find you can often avoid loops, and there's plenty of built in functions to ease your path. Unless this is a coding exercise where you have to use a prescribed method, I'd do the following one-liner to get your desired result:
D = isprime( A ) + 0.5*( A == 1 );
This relies on two simple tests:
isprime( A ) % 1 if prime, 0 if not prime
A == 1 % 1 if == 1, 0 otherwise
Multiplying the 2nd test by 0.5 gives your desired condition for when the value is 1, since it will also return 0 for the isprime test.
You are not returning anything from the function. The return value is supposed to be 'B' according to your code but this is not set. Change it to A.
You are looping k until A(i,j) which is always divisible by itself, loop to A(i,j)-1
With the code below I get [0.5,1;1,0].
function A = modifikuj(A)
[n,m] = size(A);
for i = 1:n
for j = 1:m
prost=1;
if (A(i,j) == 1)
A(i,j) = 0.5;
else
for k = 2:(A(i,j)-1)
if(mod(A(i,j),k) == 0)
prost=0;
end
end
if(prost==1)
A(i,j)=1;
else
A(i,j)=0;
end
end
end
end
In addition to #EuanSmith's answer. You can also use the in built matlab function in order to determine if a number is prime or not.
The following code will give you the desired output:
A = [1,2;3,4];
A(A==1) = 0.5; %replace 1 number with 0.5
A(isprime(A)) = 1; %replace prime number with 1
A(~ismember(A,[0.5,1])) = 0; %replace composite number with 0
I've made the assumption that the matrice contains only integer.
If you only want to learn, you can also preserve the for loop with some improvement since the function mod can take more than 1 divisor as input:
function A = modifikuj(A)
[n,m] = size(A);
for i = 1:n
for j = 1:m
k = A(i,j);
if (k == 1)
A(i,j) = 0.5;
else
if all(mod(k,2:k-1)) %check each modulo at the same time.
A(i,j)=1;
else
A(i,j)=0;
end
end
end
end
And you can still improve the prime detection:
2 is the only even number to test.
number bigger than A(i,j)/2 are useless
so instead of all(mod(k,2:k-1)) you can use all(mod(k,[2,3:2:k/2]))
Note also that the function isprime is a way more efficient primality test since it use the probabilistic Miller-Rabin algorithme.

MATLAB — How to eliminate equal matrices that are created randomly inside loop?

The code segment I'm working on is given below:
NphaseSteps = 6;
phases = exp( 2*pi*1i * (0:(NphaseSteps-1))/NphaseSteps );
i = 1;
while i <= 10 %number of iterations
ind = randi([1 NphaseSteps],10,10);
inField{i} = phases(ind);
save('inField.mat', 'inField')
i = i + 1;
end
Now, what I want is to keep track of these randomly created matrices "inField{i}" and eliminate the ones that are equal to each other. I know that I can use "if" condition but since I'm new to programming I don't know how to use it more efficiently so that it doesn't take too much time. So, I need your help for a fast working program that does the job. Thanks in advance.
My actual code segment (after making the changes suggested by #bisherbas) is the following. Note that I actually want to use the variable "inField" inside the loop for every random created matrix and the loop advances only if the result satisfies a specific condition. So, I think the answer given by #bisherbas doesn't really eliminate the equal inField matrices before they are used in the calculation. This is, of course, my fault since I didn't declare that in the beginning.
NphaseSteps = 6;
phases = exp( 2*pi*1i * (0:(NphaseSteps-1))/NphaseSteps );
nIterations = 5;
inField = cell(1,nIterations);
i = 1;
j = 1;
while i <= nIterations % number of iterations
ind = randi([1 NphaseSteps],TMsize,TMsize);
tmp = phases(ind);
idx = cellfun(#(x) isequal(x,tmp),inField);
if ~any(idx)
inField{i} = tmp;
end
j = j+1;
outField{i} = TM * inField{i};
outI = abs(outField{i}).^2;
targetIafter{i} = abs(outField{i}(focusX,focusY)).^2;
middleI = targetIafter{i} / 2;
if (max(max(outI)) == targetIafter{i})...
&& ( sum(sum((outI > middleI).*(outI < max(max(outI))))) == 0 )
save('inFieldA.mat', 'inField')
i = i + 1;
end
if mod(j-1,10^6) == 0
fprintf('The number of random matrices tried is: %d million \n',(j-1)/10^6)
end
end
Additionally, I've written a seemingly long expression for my loop condition:
if (max(max(outI)) == targetIafter{i})...
&& ( sum(sum((outI > middleI).*(outI < max(max(outI))))) == 0 )
save('inFieldA.mat', 'inField')
i = i + 1;
end
Here I want a maximum element at some point (focusX, focusY) in the outField matrix. So the first condition decides whether the focus point has the maximum element for the matrix. But I additionally want all other elements to be smaller than a specific number (middleI) and that's why the second part of the if condition is written. However, I'm not very comfortable with this second condition and I'm open to any helps.
Try this:
NphaseSteps = 6;
phases = exp( 2*pi*1i * (0:(NphaseSteps-1))/NphaseSteps );
i = 1;
inField = cell(1,NphaseSteps);
while i <= NphaseSteps %number of iterations
ind = randi([1 NphaseSteps],NphaseSteps,NphaseSteps);
tmp = phases(ind);
idx = cellfun(#(x) isequal(x,tmp),inField);
if ~any(idx)
inField{i} = tmp;
end
save('inField.mat', 'inField')
i = i + 1;
end
Read more on cellfun here:
https://www.mathworks.com/help/matlab/ref/cellfun.html

Matlab Nested Radicals

Working on an assignment in MATLAB and I can't seem to figure this problem out due to the arithmetic, I've been trying it for about 6 hours now
I need to create a loop that accepts user input > 1 (done) and loops through the following (m is input)
t1 = sqrt(m);
t2 = sqrt(m-sqrt(m));
t3 = sqrt(m-sqrt(m+sqrt(m)))
t4 = sqrt(m-sqrt(m+sqrt(m-sqrt(m))))
t5 = sqrt(m-sqrt(m+sqrt(m-sqrt(m+sqrt(m)))))
and so on until the new t value minus the old t value is < 1e-12
My current code is as follows
%Nested Radicals
clear all;
clc;
%User input for m
m = input('Please enter a value for m: ');
%Error message if m is less than 1
if m <= 1
fprintf('ERROR: m must be greater than 1\n')
m = input('Please enter a value for m: ');
end
%Error message if m is not an integer
if mod(m,1) ~= 0
fprintf('m must be an integer\n')
m = input('Please enter a value for m: \n');
end
%Nested things
t_old = m;
t_new = sqrt(m);
varsign = -1;
index = 1;
loop = true;
endResult = 1e-12;
sqrts = [sqrt(m), sqrt(m-sqrt(m)), sqrt(m-sqrt(m+sqrt(m))), sqrt(m-sqrt(m+sqrt(m-sqrt(m)))), sqrt(m-sqrt(m+sqrt(m-sqrt(m+sqrt(m)))))];
fprintf('m = %d\n',m)
fprintf('t1 = %14.13f\n', t_new')
while loop
if index ~= 1
curResult = abs(sqrts(1,index) - sqrts(1, index-1));
else
curResult = abs(sqrts(1, index));
end
if curResult > endResult
if index < 5
t_new = sqrts(1, index+1);
else
t_new = sqrts(1, index);
loop=false;
end
if index
fprintf('t%d = %14.13f\n', index, t_new)
end
else
fprintf('t%d = %14.13f\n', index, t_new);
break;
end
index = index + 1;
if index > 50
fprintf('t%d = %14.13f\n', index, t_new);
break;
end
end
Unless I'm very much mistaken, you can write the expression for t(n) as follows:
t(n) = sqrt(m-sqrt(m+t(n-2));
which makes it a lot easier to loop:
%Nested Radicals
clear all;
clc;
%User input for m
m = input('Please enter a value for m: ');
%Error message if m is less than 1
if m <= 1
fprintf('ERROR: m must be greater than 1\n')
m = input('Please enter a value for m:');
end
%Error message if m is not an integer
if mod(m,1) ~= 0
fprintf('m must be an integer\n')
m = input('Please enter a value for m:');
end
%Nested things
t_old = sqrt(m);
t_new = sqrt(m-sqrt(m));
threshold = 1e-12;
k = 3;
while abs(t_new - t_old) >= threshold
temp = sqrt(m-sqrt(m+t_old));
t_old = t_new;
t_new = temp;
k = k+1;
end
fprintf('t%d = %14.13f\n', k-2, t_old);
fprintf('t%d = %14.13f\n', k-1, t_new);
fprintf('t%d - t%d = %14.13f\n', k-2, k-1, t_old - t_new);
which gives for m=9 for example:
Please enter a value for m: 9
t17 = 2.3722813232696
t18 = 2.3722813232691
t17 - t18 = 0.0000000000005
I'm not sure what you're trying to do with the sqrts variable, you should be calculating each step on the fly in your loop, since you can't possibly know how deep you need to go
m = 5; % Get m however you want to
n = 0; % Iteration counter
tol = 1e-12 % Tolerance at which to stop
dt = 1; % initialise to some value greater than 'tol' so we can start the loop
% Loop until tn is less than tolerance. Would be sensible to add a condition on n,
% like "while tn > tol && n < 1000", so the loop doesn't go on for years if the
% condition takes a trillion loops to be satisfied
while dt > tol
% Set the value of the deepest nested expression
tn = sqrt(m);
% We know how many times take sqrt, so for loop our way out of the nested function
% Initially we want the sign to be -1, then +1, -1, ...
% This is achieved using ((-1)^ii)
for ii = 1:n
tn = sqrt(m + ((-1)^ii)*tn); % Calculate next nested function out
end
% Increment iteration number
n = n + 1;
dt = abs( t_old - tn );
t_old = tn;
end
I've not done any analysis on your function, so have no idea if it's guaranteed to converge to some value <1e-12. If it isn't then you definitely need to add some maximum iteration condition as I suggest in the comments above.

Smallest integer greater than or equal to harmonic series of input

I'm working on the following problem:
I realize my code is a bit off, but I want to create a for loop that will determine whether or not the integer x (the input value) is at least less than or equal to the sum of a harmonic series.
Here is what I have so far:
function n =one_per_n(x)
if x > 10000
n = -1;
end
total = 0;
i = 0;
for i = 1:10000
if x >= total
n = ceil(total);
else
total = (1/i) + total;
end
end
I've added my attempt at a while loop. I realize it's wrong, but any help would be appreciated.
function n =one_per_n(x)
if x > 10000
n = -1;
end
total = 0;
i = 0;
for i = 1:10000
while total <= x
total = (1/i) + total;
end
end
n = total;
you don't need to use some loops:
function n = one_per_n(x)
lim = min(10000,exp(x));
value = cumsum(1./(1:lim));
n = find(value >= x,1);
if isempty(n)
n = -1;
end
A while loop is a better option in this case I think
function [total, n] = one_per_n(x)
% This is a good initial check, good work
if x > 10000
n = -1;
return;
end
% Initialize the variables
total = 0;
n = 0;
% While not finished
while (total < x)
% Number of terms
n = n + 1;
total = total + 1/n;
end
end

Matlab error : Subscript indices must either be real positive integers or logicals

I have the following error in MATLAB:
??? Subscript indices must either be real positive integers or
logicals.
Error in ==> Lloyd_Max at 74 D(w_count) = mean((x -
centers(xq)).^2);
This is my code :
function [ xq,centers,D ] = Lloyd_Max( x,N,min_value,max_value )
%LLOYD_MAX Summary of this function goes here
% Detailed explanation goes here
x = x';
temp = (max_value - min_value)/2^N;
count=1;
for j=0:temp:((max_value - min_value)-temp),
centers(count) = (j + j + temp )/2;
count = count + 1;
end
for i=1:length(centers),
k(i) = centers(i);
end
w_count = 0;
while((w_count < 2) || (D(w_count) - D(w_count - 1) > 1e-6))
w_count = w_count + 1;
count1 = 2;
for i=2:(count-1),
T(i) = (k(i-1) + k(i))/2;
count1 = count1 +1 ;
end
T(1) = min_value;
T(count1) = max_value;
index = 1;
for j=2:count1,
tempc = 0;
tempk = 0;
for k=1:10000,
if(x(k) >= T(j-1) && x(k) < T(j))
tempk = tempk + x(k);
tempc = tempc + 1;
end
end
k(index) = tempk;
k_count(index) = tempc;
index = index + 1;
end
for i=1:length(k),
k(i) = k(i)/k_count(i);
end
for i=1:10000,
if (x(i) > max_value)
xq(i) = max_value;
elseif (x(i) < min_value)
xq(i) = min_value;
else
xq(i) = x(i);
end
end
for i=1:10000,
cnt = 1;
for l=2:count1,
if(xq(i) > T(l-1) && xq(i) <= T(l))
xq(i) = cnt;
end
cnt = cnt +1 ;
end
end
D(w_count) = mean((x - centers(xq)).^2);
end
end
and i call it and have these inputs :
M = 10000
t=(randn(M,1)+sqrt(-1)*randn(M,1))./sqrt(2);
A= abs(t).^2;
[xq,centers,D] = Lloyd_Max( A,2,0,4 );
I tried to comment the while and the D, Results :
I got the xq and the centers all normal, xq in the 1-4 range, centers 1-4 indexes and 0.5-3.5 range.
I dont know whats going wrong here...Please help me.
Thank in advance!
MYSTERY SOVLED!
Thank you all guys for your help!
I just putted out of the while the for loop :
for i=1:10000,
if (x(i) > max_value)
xq(i) = max_value;
elseif (x(i) < min_value)
xq(i) = min_value;
else
xq(i) = x(i);
end
end
and it worked like charm.... this loop was initilizing the array again. Sorry for that. Thank you again!
There is an assignment xq(i) = x(i) somewhere in the middle of your function, but you pass A as x from outside where you calculate A from t which is sampled by randn, so you can't promise xq is an integer.
I'm not sure exactly what you are aiming to do, but your vector xq does not contain integers, it contains doubles. If you want to use a vector of indices as you do with centers(xq), all elements of the vector need to be integers.
Upon a little inspection, it looks like xq are x values, you should find some way to map them to the integer of the closest cell to which they belong (i'm guessing 'centers' represents centers of cells?)