next prime number using While loops
정보
This question is locked. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
이전 댓글 표시
We have to write a function called next_prime that takes a scalar positive integer input n. Use a while-loop to find and return k, the smallest prime number that is greater than n. we may use isprime function. plz help..
댓글 수: 4
Masum Mushfiq Ishti
2022년 5월 8일
편집: Jan
2023년 2월 22일
This worked for me:
function k=next_prime(n)
if (~isscalar(n)||(n<0))
fprintf('error\n');
return
end
n=n+1;
while true
if isprime(n)
k=n;
break;
else
n=n+1;
end
end
Suleman
2023년 2월 22일
what do you mean by break ? @Masum Mushfiq Ishti
채택된 답변
추가 답변 (9개)
Giancarlo milon
2021년 6월 29일
You just want the next prime so you can just do
function k = next_prime(n)
k = n + 1
% now k = input + 1
while isprime(k) == 0
% if the k is not prime add 1 till its prime
k = k+1;
% when its prime thats the answer end the loop
end
end
댓글 수: 3
Rik
2021년 6월 29일
Direct complete solutions to homework questions are discouraged, as they tend to encourage cheating. Why did you post this?
Giancarlo milon
2021년 7월 23일
i'm posting other type of solutions, if you want to cheat that's you. I'm not forcing anyone to cheat, that's your desicion. Everyone is responsible for their own actions.
Rik
2021년 7월 23일
I would question how other this is from other solutions. This is still a while loop with a 1 step increment.
I don't question your intentions, but I do question what the most likely use would be. At least your solution is documented, which is more than can be said from most homework-solutions.
Shubham Sangle
2019년 7월 10일
1 개 추천
This is link of answer to similar question https://stackoverflow.com/questions/2468412/finding-a-prime-number-after-a-given-number
Answer mentioned in above link mentions:
Some other methods have been suggested and I think that they are good, but it really depends on how much you want to have to store or compute on the spot. For instance if you are looking for the next prime after a very large number, then using the Sieve of Eratosthenes might not be so great because of the number of bits you would need to store.
Alternatively, you could check all odd integers between (and including) 3 and sqrt(N) on every number odd number N greater than the input number until you find the correct number. Of course you can stop checking when you find it is composite.
If you want a different method, then I would suggest using the Miller-Rabin primality test on all odd numbers above the input number (assuming the input is > 1) until a prime is found. If you follow the list, located at the bottom of the page, of numbers a to check for the given ranges, you can significantly cut down on the number of as you need to check. Of course, you might want to check at least a few of the smaller primes (3,5,7,11 for instance) before checking with Miller-Rabin.
댓글 수: 1
John D'Errico
2020년 5월 10일
편집: John D'Errico
2020년 5월 10일
For a little expansion on the ideas mentioned here...
A rough number is a number that is divisible by no small primes. A k-rough number is a number that is divisible by no prime less than k. That allows us to define the extent that a number is known to be rough. (Some definiitions would have that inequality be less than, others would say less than or equal to. The difference is not really important here.)
Rough-ness is useful because it can help you to exclude numbers from testing them using isprime, because isprime is somewhat computationally intensive. Excluding all even numbers from a test essentially allows you to exclude half the numbers from testing to see if they are prime. But then you might also like to exclude all numbers divisible by 3, then 5, 7, 11, etc.
A simple test to identify 42-rough numbers is easy to implement using gcd.
prod(primes(41))
ans =
304250263527210
log2(prod(primes(41)))
ans =
48.1122518409569
So we see the product of all primes no larger than 41 is small enough that it fits perfectly into the dynamic range of a double precision integer. And if we could exclude all numbers that have at least one prime factor no larger than 41, we would manage to exclude roughly 85% of all integers.
1 - prod(1 - 1./primes(41))
ans =
0.854906329597798
For example, is the number 1e9+1 a 41-rough number? GCD will tell us.
gcd(prod(primes(41)),1e9+1)
ans =
19019
No. It has at least one small prime factor, here we see that to be 3. It may have multiple factors of 3, but we really don't care, since we know now that 1e9+1 cannot possibly be prime.
In fact, if we consider the next 10 integers that exceed 1e9, how many are 41 rough?
gcd(prod(primes(41)),1e9 + (1:10))
ans =
19019 6 23 82 15 2 1 42 1 170
The idea is to look only for numbers that have a gcd of exactly 1 with our product of small prime, since that implies the number is not divisible by any of them.
So we immediately know that of the integers following 1e9, only 1e9+7 and 1e9+9 can possibly be prime, because only they are 41 rough.
isprime(1e9+[7 9])
ans =
1×2 logical array
1 1
In fact, they are both prime numbers. If we wanted to find more primes exceeding 1e9, we could just do:
kr41 = find(gcd(prod(primes(41)),1e9 + (1:50)) == 1)
kr41 =
7 9 13 19 21 31 33 37
isprime(1e9 + kr41)
ans =
1×8 logical array
1 1 0 0 1 0 1 0
So only 8 explicit calls to isprime were needed, and half of those tests were successful in identifying a prime number.
BHARAT JAWLE
2021년 2월 4일
편집: BHARAT JAWLE
2021년 2월 4일
function k=next_prime(n)
k=n+1;
while factor(k)~= k
k=k+1;
end
댓글 수: 2
Rik
2021년 2월 4일
You can solve it like this, but do you actually understand why this works? Do you check the output of the factor function for non-primes? Did you check what while does for non-scalar inputs?
Rik
2021년 2월 4일
@BHARAT JAWLE You did not edit anything I could notice about your answer. Can you answer the questions in my previous comment?
RP
2019년 4월 10일
I was working on that exercise too and I tried
function next_prime(n)
x=n
while isprime(x) = 0
x = n+1
end
however, Matlab returns "The expression to the left of the equals sign is not a valid target for an assignment."
댓글 수: 5
You need to read the documentation for every operation that you use, no matter how trivial you think it is. Then you would learn the difference between = (allocation) and == (logical equivalence). In any case, a more MATLAB-ish solution is to use ~ :
if ~isprime(x)
You also forgot to specify any output argument: read the documentation to know how to define functions with input/output arguments
RP
2019년 4월 10일
Thank you for the tip! Unfortunately the function is still not doing what it's supposed to do and I see that it doesn't look right, but I don't really know how to fix it.
You forgot to define an output argument.
Also you never increment n, so x is always just n or n+1, nothing more. Try this:
function n = next_prime(n)
n = n+1;
while ~isprime(n)
n = n+1;
end
end
Xenium Adil
2019년 4월 10일
Stephen23
2019년 4월 10일
>> next_prime(5) % wrong
ans = 5
>> next_prime(7) % wrong
ans = 7
>> next_prime(8) % infinite loop until I press ctrl+c
>>
Your function either returns an incorrect value or goes into an infinite loop. You really need to test your code and read the comments in this thread.
VIGNESH B S
2021년 10월 14일
편집: VIGNESH B S
2021년 10월 14일
function answer = next_prime(n)
%the function recieves a scalar 'n'
flag = 1;
% a variable flag will act as break statement (helps to break out of while loop when its value is changed to 0).
n = n+1;
% We are adding 1 to the scalar n because the question asks about the next prime to 'n'.
% ( so if n is a prime this function returns the same n because this function is to find primes... but we actually want next prime to n not n itself).
while flag == 1 % Then comes the while loop to check whether it is a prime or not
if isprime(n) == 1
flag = 0; % if it is prime it breaks out of while loop
% ( as flag is made from 1 to 0 and while is only if flag == 1).
else
n = n + 1; % check for prime if not add 1 .... till a prime next to n is obtained .
end
end
answer = n;
end
댓글 수: 4
Rik
2021년 10월 14일
Why did you post this answer? What does it teach? You're more than welcome to start answering questions, but why post a solution to a homework question without any explanation?
If you don't respond this answer will be deleted.
Rik
2021년 10월 14일
You didn't understand my point. I personally understand what you're doing. But I'm not the intended audience. You posted a solution for a homework question. That means your audience consists of fellow students. They can do two things with your post: learn and cheat.
To be able to learn from your code they must understand it. Your code doesn't contain any comments, so they can only understand it if they already understand what they should do. If they already understand, why would they bother reading this?
So the only thing they can do here is cheat.
If you don't comment your code, how can a student who can't already solve this on their own learn from what you post? (this is not a rhetorical question)
Also, your code is also fairly complex when you compare it to other posts in this thread that do essentially the same.
VIGNESH B S
2021년 10월 14일
Hope the code is fine now. BTW im new to community and got carried away in solvign and answering questions... so i thought the commenting part was not necessary .. Now its clear .Thank You !!!
Rik
2021년 10월 14일
You're most welcome to start answering questions, but I would suggest you don't answer any homework questions. You can find guidelines for posting homework on this forum here, I'll leave it to you to extend them to the answering of homework.
If you just want to practice solving puzzles with Matlab, I can recommend Cody. It will not reward good coding skills, but you will have many different problems you can solve.
Zia Ur Rehman
2022년 8월 25일
My code is running very well.
if there is any mistake plz mention me because I'm very new in coding.
function k = next_prime(n)
k =n+1;
while ~isprime(k)
k=k+1;
end
end
댓글 수: 1
Rik
2022년 8월 25일
Why did you post this answer? What does it teach? You're more than welcome to start answering questions, but why post a solution to a homework question without any explanation?
Your code works, but it is far from optimal. To understand what you can do to improve it, you should read the accepted answer.
Aziz ur Rehman
2023년 1월 28일
Simple as that
function Final_Prime=next_prime(n)
prime=primes(n+n) ; i=1
temp=prime(1);
while prime(i)<=n
i=i+1;
temp=prime(i);
end
Final_Prime=temp;
댓글 수: 4
Aziz ur Rehman
2023년 1월 28일
it is just another simple approach for finding the answer.
Rik
2023년 1월 28일
I can't tell why this would work, be efficient, or how this would be simple. Can you explain it? Where is primes coming from? Why are you using an array?
@Aziz ur Rehman: This apporach is complicated and inefficient.
prime = primes(n+n);
If n is large, e.g. 4e14, calulating all primes until 2*n is expensive.
There is no need to introduce the temporary variable "temp". Simply use the output directly.
Checking all primes, if they are smaller equal than n is a waste of time also.
A simplified (but still less efficient) version of your code:
function m = next_prime(n)
prime = primes(n+n); % ???
i = 1;
while prime(i) <= n
i = i + 1;
end
m = prime(i);
Does this work? Well, yes, but in a terribly inefficient way. (I'm sorry, but that is true.)
First, for a given value of n, this computes ALL prime numbers up to 2*n. If n is at all large, for example, 1e9.
numel(primes(2e9))
So in that case, it generates just under 100 million primes, requiring a little under 1 gigabyte of RAM to store them all.
Then it tests EVERY one of those primes, starting at the first prime (which is 2), and compares that number to n. Is it greater than n? If not, then it looks at the next prime in the list of all primes.
The code relies on something that not all people know (ok, Bertrand and Chebyshev knew it)
i.e., that there always exists at least one prime in the interval [n,2*n]. When n is small, this is not so problematic. However, I think you would not want to find the next prime larger than say 1e15 with the code by @Aziz ur Rehman.
nextprime(sym(1e15))
The code in this answer is massive overkill. The mathematical equivalent to using a Mack truck to carry a pea to Boston. Rather than just finding the next prime, it first generates potentially millions, or even billions of primes, and then looks to see which one is greater than n. And it does that search very ineffiiciently.
Could this code have been written more efficiently? If a while loop is an absolute imperative, AND the value of n is not too large, AND you cannot use a tool like find, then a while loop does work. But as I said, one can use a Mack truck to carry a pea to Boston. But that does not mean I want to do so as this code was written. For example, had the author used a simple bisection search in that vector of all primes, I would have given the code some grudging respect. And you could write that using a while loop.
RAVI RANJAN
2023년 2월 14일
function k = next_prime(n)
total = 0;
k = 0;
if isprime(n) == 1
k = n + 1;
else
while isprime(n) == 0
n = n + 1;
k = n;
end
end
fprintf('next prime number = %d',k)
댓글 수: 1
You define variables that are never used. What is the purpose of total in there for? Except to dump CPU cycles on the floor?
And your code will not work. If you are going to publish code that claims to give a solution to a problem, surely you would actually test the code? I've copied it directly into this comment. I even left total in there. I did need to add an extra end to the code so it would run though.
Now try that exact code, when n is a prime number. What is the next prime after 7?
k = next_prime(7)
Oh, yes. Now I remember. 8 is a prime number. Wow! How could I have forgotten that 8 is prime? Your code works really well. NOT.
function k = next_prime(n)
total = 0;
k = 0;
if isprime(n) == 1
k = n + 1;
else
while isprime(n) == 0
n = n + 1;
k = n;
end
end
end
Aramis
2024년 2월 6일
THE BEST ANSWER
function k = next_prime(n)
k=n;
while isprime(k)==false || k==n
k = k+1;
end
end
댓글 수: 1
Stephen23
2024년 2월 7일
SOME IMPROVEMENTS
The loop condition can be simplified by simply incrementing k before the loop (just as some comments on this thread already show). Note that such an increment occurs just once whereas your approach calls EQ and && on every loop iteration.
Using EQ on logical values is not required. Use NOT instead.
This question is locked.
카테고리
도움말 센터 및 File Exchange에서 Number Theory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
