not urgent, but if you see this and have time please help me, thank you , Please help , LAST prime under n

1 view (last 30 days)
I need to write a code which the instruction is below, I tried all I could, but I don't know how to store the last element and find the prime factors of the next number, please read, your help will change my grade dramatically, I appreciate so much if you help, this is due tomorrow and I just found out about this website, if you see this and know about matlab please help.
Calculate the largest prime numbers below 5000, 10000, and 100000. Calculate the largest prime factor of the next integer above your prime. Your answer will be six numbers. Three primes, and three largest prime factors of the next integer. You may use the isprime and factor commands, but you will lose points for using the primes command in your submission (though you may check your work with it). Example: Calculate the largest prime below 10. This number is 7, which you may obtain by whatever method you prefer (trial division is easy to understand and loops well). The next integer above this prime number is 8. The largest prime factor of 8 is 2. Thus, the answers for a limit of 10 are: 7 as the prime, 2 as the largest prime factor of the next number
what I have so far:
n=1000000;
i=1:n;
isprime=true(1,n);
isprime(1)=false;
p=2;
isprime(2*p:p:end)=false;
p=3;
while p^2<=n
while ~isprime(p) && p^2<=n;
p=p+1;
end;
if ~isprime(p)
break;
end ;
isprime(2*p:p:end)=false;
p=p+2;
disp('isprime(nth)')
end;
primesfound=find(isprime)

Accepted Answer

Matt Fig
Matt Fig on 11 Sep 2012
Edited: Matt Fig on 11 Sep 2012
O.k., you gave it a good shot, but there are some simple mistakes here. You want to use the ISPRIME function, but you define a variable named isprime. This is a big no-no. Look what happens:
clear all
pi % Call the function.
pi=4; % Create a variable.
pi % Now try to call the function again! Oops!
So change your variable name to ispr or something similar so you don't mask the function you need to call.
That one thing will go a long way towards clearing this up. At the end of your code, put this. You will find some useful hints here.
lastprime = primesfound(end);
nextinteger = lastprime+1;
% use this to Call FACTOR function inside the MAX function.....
  7 Comments
Andrei Bobrov
Andrei Bobrov on 11 Sep 2012
without functions isprime and factor
A = [5000, 10000, 100000];
out = zeros(2,numel(A));
out(1,:) = A - 1 + rem(A,2);
for jj = 1:numel(A)
while ~all(rem(out(1,jj),3:2:out(1,jj)-2))
out(1,jj) = out(1,jj) - 2;
end
q = [2,3:2:out(1,jj)];
q2 = q(~rem(out(1,jj)+1,q));
k = q2(1);
for j1 = 2:numel(q2)
if all(rem(q2(j1),[2,3:2:q2(j1)-1])) && q2(j1) > k
k = q2(j1);
end
end
out(2,jj) = k;
end

Sign in to comment.

More Answers (0)

Categories

Find more on Startup and Shutdown 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!