필터 지우기
필터 지우기

how do i determine the output of how many prime numbers are there and list them by the function that i created?

조회 수: 2 (최근 30일)
I have created my own function(without using isprime or any other built in functions) to determine whether an integer is a prime number or not. But I need to call the function that I created and input a range of numbers [10 20] and the output should be there are 4 prime numbers btwn 10 and 20 which are 11 13 17 19. I have attached the function that I have created. Thanks I am new to matlab.

채택된 답변

Geoff Hayes
Geoff Hayes 2015년 11월 28일
Rather than have your function MyPrime output strings indicating whether the number is prime or not, consider changing the outputs to a zero (false or not prime) or (true or prime). With the boolean output, you can more easily determine which numbers (from your array) are prime or not. Suppose that MyPrime returns a zero or one, and consider the following
myIntegers = 10:20; % create a list of integers between 10 and 20
You can use the arrayfun to apply your MyPrime function to each integer with the output being an array of ones and zeros.
primeOrNot = arrayfun(@(k)MyPrime(k),myIntegers);
If element k of primeOrNot is a one, then you know that the kth element of myIntegers is a prime. To extract these numbers just do
myIntegers(logical(primeOrNot))
which gives us an answer of
ans =
11 13 17 19
Note that the cast of primeOrNot as logical is necessary to access the elements of myIntegers. You can avoid this cast if your output from MyPrime is true or false rather than 1 or zero respectively.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by