How to determine if a number is prime?
    37 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Juan Zegarra
 el 1 de Mayo de 2019
  
    
    
    
    
    Respondida: Ozkan
 el 8 de Mayo de 2023
            Hello, I was wondering if you can help how to determine if numbers from 0 to 100 are prime. Should I use loops? Please I am really confused with this homework.
2 comentarios
  Rik
      
      
 el 1 de Mayo de 2019
				There are many ways you could solve this. What was the exact assignment? I suspect you're not allowed to use the isprime function.
How would you solve this on paper? That's usually a good start for how to solve it in any programming language.
You can find guidelines for posting homework on this forum here (and there is also a lot of helpful advice on that page).
Respuesta aceptada
  jahanzaib ahmad
      
 el 2 de Mayo de 2019
        
      Editada: jahanzaib ahmad
      
 el 2 de Mayo de 2019
  
      thats not difficult .try to solve it on paper first .for example u have a number 100 . how will u check that its prime or not ?
divide it with all numbers from 1 to 99 .. and if any time the remainder is zero its not a prime number 
to divide 100 from 1 to 100 u can use for loop .
1 comentario
  Rik
      
      
 el 2 de Mayo de 2019
				As is probably mentioned in the links posted above, you don't need to check up to 99, checking up to the square root of your number (and exiting the loop when you found a factor) will get you a big jump in performance.
An even better method would be to write a prime number sieve (use ismember to find the multiples).
Más respuestas (1)
  Ozkan
 el 8 de Mayo de 2023
        % First n terms of Fibonacci series
n = 55;
% Starting with the first two terms are 1 and 1 
fibo = [1, 1];
% Calculate the remaining terms and add them into the serie
for i = 3:n
    fibo(i) = fibo(i-1) + fibo(i-2);
end
% Create a pointer vector to point the prime numbers
prime_flags = false(size(fibo));
% Check if the term in the serie is a prime number
for i = 1:n
    % Prime numbers start from 2, thus no need to check the first two terms
    if i > 2
        % Check each number
        for j = 2:sqrt(fibo(i))
            % If division has no remainder, it is not a prime number
            if rem(fibo(i), j) == 0
                break;
            end
        end
        % If there is no integer divider then it is a prime number
        if rem(fibo(i), j) ~= 0
            prime_flags(i) = true;
        end
    end
end
% find the indices of prime flags
prime_indices = find(prime_flags);
disp(fibo);
disp(prime_indices)
0 comentarios
Ver también
Categorías
				Más información sobre Performance and Memory en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!




