Crivo de Eratóstenes

Encontrar números primos é um problema comum em olimpíadas e maratonas de programação. Até hoje não existe uma maneira fácil de determinar se um número é ou não primo, mas para resolver estes problemas é indispensável o conhecimento de alguns algoritmos clássicos e simples, como o Crivo de Eratóstenes.

O Crivo de Eratóstenes é um método bastante prático para encontrar os primos de 2 até um valor limite, que pode ser feito a mão e é fácil de implementar.

O algoritmo consiste em:

  1. Determinar (ou receber na entrada do programa) o valor limite, isto é, o maior número que desejamos saber se é primo.
  2. Fazer a raiz quadrada do valor limite. Pode-se arredondar para baixo caso a raiz não seja exata (e quase nunca é).
  3. Criar um vetor (lista) com os números de 2 até o valor limite.
  4. Para i=2 até raiz do valor limite, caso o número (i) não esteja riscado insira-o na lista dos primos (ou imprima-o, ou não faça nada, isso depende da utilidade que você quer dar para o crivo) e risque todos os seus múltiplos na lista.

Há várias maneiras de implementar este algoritmo. Eu pseudocodaria (meu pseudocódigo é bem próximo de uma linguagem normal, porque acho que assim é mais fácil de entender e depois implementar) ele assim:

/* Primeiro passo */
recebe valorLimite

/* Segundo passo */
raiz [tex]\leftarrow[/tex] [tex]\sqrt{valorLimite}[/tex]

/* Terceiro passo */
para i [tex]\leftarrow[/tex] 2 até valorLimite
    vetor[i] [tex]\leftarrow[/tex] i
fim-para

/* Quarto passo */
para i [tex]\leftarrow[/tex] 2 até raiz
    se vetor[i] = i
        imprima "O número " i " é primo."
        para j [tex]\leftarrow[/tex] i+i até valorLimite, de i e i
            vetor[j] [tex]\leftarrow[/tex] 0
        fim-para
    fim-se
fim-para

Vêem como é simples?

Crivo de Eratóstenes implementado em C

#include
#include
// necessário para raiz

#define NMAX 1000000 // valor máximo para o valor máximo

int main() {
int i, j, vetor[NMAX];
int valorMaximo, raiz;

// Primeiro passo
scanf("%d", &valorMaximo);

// Segundo passo
raiz=sqrt(valorMaximo);

// Terceiro passo
for (i=2; i<=valorMaximo; i++) {
vetor[i]=i;
}

// Quarto passo
for (i=2; i<=raiz; i++) {
if (vetor[i]==i) {
printf("%d é primo!\n", i);
for (j=i+i; j<=valorMaximo; j+=i) {
vetor[j]=0; // removendo da lista
}
}
}

return 0;
}

No USACO Training Program Gateway (programa de treinamento para olimpíadas dos estado-unidenses) há um problema muito interessante (Prime Palindromes) cujo objetivo é determinar palíndromos primos de X a Y. Uma das melhores situações que já encontrei para usar o Crivo e sem dúvidas é um ótimo treinamento. Além de determinar primos, você terá que determinar palíndromos e é outro ótimo exercício lógico-matemático.

Divirtam-se e qualquer dúvida usem os comentários!

9,253 thoughts on “Crivo de Eratóstenes

  1. Мягкая черепица – современный кровельный материал с повышенными техническими характеристики, которые соответствуют практически всем заданным требованиям. Мягкая черепица может быть использована на крыше любого типа, но чаще применяется для кровли домов, коттеджей, загородных поместий, подробнее об этом читайте на сайте roofor.ru

  2. He added that Western countries supported extremist groups in Syria in an attempt to bring down alAssad, a repeat of what they had done in Afghanistan in the face of Soviet Union. The virus has approached a lot of my players, but for him it is too much. For many years, people thought that though you get your heart rate between 60% to 70% of this maximum pulse rate, you will definitely maximize fat burning and reduce weight faster.”Newcastle manager Alan Pardew, who handed a debut to 17yearold forward Adam Armstrong, reserved his praise for 21yearold Spanish striker Ayoze Perez, who proved a handful for the home defence.In 1943streptomycin was located inside of Streptomyces griseus and it was verified to totally inhibit the bacterial strains.
    Dalvin Cook Vikings Jersey

  3. I really wanted to make a quick word in order to thank you for all the remarkable techniques you are placing on this website. My prolonged internet lookup has at the end of the day been paid with sensible points to go over with my contacts. I would mention that many of us website visitors actually are definitely endowed to exist in a superb network with many outstanding professionals with beneficial solutions. I feel extremely fortunate to have encountered your entire web page and look forward to some more amazing times reading here. Thanks once more for all the details.

  4. Монтаж инженерных сетей в столице должен выполняться грамотными мастерами. Если вам потребуется монтаж электропровода в доме, или приобретение допускающих нормативно-правовых актов, предлагаем обратиться к мастерам по этому вопросу переходите по ссылке – подключение электричества

    На center-energo.com вам подскажут как разобраться во всех вопросах. Сотрудники предоставляют разные услуги по электроснабжению загородных домов и фабрик. Именно поэтому присоединение к электросетям есть их главным направлением.

    Центр Энергетических Решений и Инноваций – это сформировавшаяся компания на рынке предоставления услуг в сегменте рынка электрических услуг и снабжения. Инженеры предоставляют поддержку в Москве и ближайших населенных пунктах страны. Если вам понадобиться price list на электромонтажные работы, вы можете связаться со специалистами по телефону +7 (495) 2015-077, где вам предоставят ответы на интересующие вас вопросы и расскажут всё необходимое.

    Если за работу на дачном участке не желают браться другие организации, прокладка кабельных линий с поддержкой сотрудников ООО будет незамедлительной и успешной.

    Ведь в организации работают настоящие профессионалы, а сама фирма находится по адресу г. Москва, ул.Верхняя Красносельская, д.34, пом.V, комн. 2Г. Если Вас заинтересует стоимость электромонтажных работ, звоните по контактам фирмы, где менеджеры проконсультируют Вас по ключевым моментам.

  5. I precisely wished to thank you so much yet again. I do not know what I might have made to happen in the absence of the entire opinions revealed by you on that subject. It had been a frustrating situation for me, but being able to see the specialised style you handled that made me to leap over contentment. Now i am grateful for the assistance and then sincerely hope you really know what an amazing job that you are getting into teaching the rest using your web site. Most probably you haven’t got to know all of us.

  6. Symptoms:Symptoms of kidney cancer include:a. Newest therapy approaches like the Macrolides or the blend of Betalactamase and Betalactams have not been yet sufficient studied. If not try checking out this story on feros guide for other Rift game tips.Sometimes she does it, other times she does not. An useful source of calcium supplement are milk products, for example soy products whole milk.
    Marwan Mohsen Egypt Jersey

  7. 52 percent, to 4,396. Chantix has the potential to diminish the sense of satisfaction associated with smoking. But the chemo was to dangerous poisonous and could not be employed in healing Tuberculosis.If you are going to operate a bar and also restaurant that serves drinks, you really need to have the right equipment for the responsibility.Unilateralism by the United States after the 9/11 attacks in 2001 sowed the seeds for violence which would not be unrooted in decades, he said.
    http://www.worldjerseysshop.com/Cheap-Green-Bay-Packers-Montravius-Adams-Jersey-Wholesale/

  8. Borders are formed by binding which holds the pleats in location at leading and bottom. Valj Semerenko, Ukraine, 11.”In the first set, Federer broke for a 42 lead, but Djockovic broke back immediately in the next game but Federer missed two set points before the set needed to be decided by a tiebreak. A mobile phone application should be actually created to become utilized on all the numerous cell phones and also tablet computers, produced through unique brand names featuring Apple, Samsung and also others. Impressed with the results, you go out and buy similar shoes, thinking that perhaps they will help you achieve better results.
    Wholesale Jerseys From China

  9. McGuire: “There’s a great future in plastics.Atomizer: The atomizer vaporizes the nicotine solution held in cartridge.Neid’s contract expires in 2016.Li is scheduled to attend a series of activities in Brussels, including a ChinaEU business summit, a ChinaEU dialogue on innovation cooperation, a signing ceremony of cooperation documents between small and mediumsized enterprises, and activities marking the ChinaEU year of tourism, according to Hua.papier pour cartonnageBEIJING, May 22 (Xinhua) Chinese Premier Li Keqiang will pay an official visit to Germany and Belgium from May 30 to June 2, according to Chinese Foreign Ministry spokesperson Hua Chunying on Monday.
    Wholesale Baseball Jerseys China

  10. Недавно анализировал материалы инет, вдруг к своему восторгу обнаружил прелестный ресурс. Ссылка на него: https://zaxvatu.net/internet/ . Для меня данный сайт оказался очень нужным. До встречи!

  11. When you train outdoors, there are plenty of distractions, comparable to stoplights, cars and individuals that take your mind off, or protect you from training at a given degree intensity in order to boost fat burning.Things returned to normal at the park after experts explained the reasons behind the jumping fish, all of which were returned to the lake.That may be it.Angelina began her diet by eating healthy.Who else should we think of but Pamela Anderson?This girl shuns chicken, red meat, seafood and even fish.
    Edward Pequeno College Jersey

  12. A lot of thanks for all your effort on this blog. Gloria really likes participating in investigations and it is simple to grasp why. Almost all notice all of the lively tactic you offer precious ideas by means of this web blog and therefore cause contribution from website visitors on this subject matter then my simple princess is truly discovering a whole lot. Take pleasure in the rest of the new year. You are doing a dazzling job.

  13. This is simply because they sell any kind of automobile. Some have taps just above the ac unit while others have that taps right at an individual side.Shen Chunyao, chairman of the Legislative Affairs Commission of the National People’s Congress (NPC) Standing Committee, delivered the report Sunday at the bimonthly session of the NPC Standing Committee, which runs until Wednesday. Tomorrow (Saturday) morning, they have free time and rest because recovery is much more important than a training session now. The S&P 500 fell 8.
    http://www.uknbashop.com/Cheap-Washington-Wizards-Ramon-Sessions-Jersey-Uk/

  14. SocialUpExpress.com – Top SMM Panel

    The top #1 automated social media reseller panel, we offer the best prices for Facebook, Instagram, Twitter, YouTube and others.
    http://bit.ly/socialupexpress

    ⬇⬇⬇ OUR SERVICES ⬇⬇⬇

    YOUTUBE SERVICES:
    Buy YouTube Views
    Buy Youtube Targeted Views
    Buy Youtube Adwords Views
    Buy Youtube Live Stream
    Buy YouTube Shares
    Buy Youtube Subscribers
    And More! http://bit.ly/socialupexpress

    INSTAGRAM SERVICES:
    Buy Instagram Followers (Guaranteed)
    Buy Instagram Followers (No Refill)
    Buy Instagram Followers/Likes (MALE,FEMALE)
    Buy Instagram Story/Poll/Impressions/Saves
    Buy Instagram Likes
    Buy Instagram Views
    Buy Instagram Live Video
    Buy Instagram TV Views
    Buy Instagram Auto Like + Views – 30 Days Membership
    Buy Instagram Auto Likes/Views/Comments
    And More! http://bit.ly/socialupexpress

    FACEBOOK SERVICES:
    Buy Facebook Page Likes
    Buy Facebook Post Likes + Emoticons
    Buy Facebook Views + Live Views
    Buy Facebook Followers
    Buy Facebook & Others
    And More! http://bit.ly/socialupexpress

    TWITTER SERVICES:
    Buy Twitter Followers
    Buy Twitter Retweets
    Buy Twitter Likes/Favorites
    Buy Twitter Comments/Live/Views/Impressions
    Buy Twitter Poll Votes
    Buy Twitter Auto Retweets/Favorites
    And More! http://bit.ly/socialupexpress

  15. JLo began exercising at a young age. While it is better to not necessarily utilize either, if you are going to make use of it, use butter as opposed to margarine as margarine contains trans fats. Dairy and mozerella get high extra fat quantities, and rather than chopping them beyond healthful eating completely, have them in a more practical, lowfat way.Nowadays, she has a fitness trainer based in Los Angeles and classes of yoga.The employee said that an audition for a singing contest was being held at the time, which generated a lot of loud noise that spooked the fish.
    http://www.ukmlbshop.com/Cheap-Chicago-White-Sox-Harold-Baines-Jersey-Uk/

  16. О нем отзывов. Кто пробовал,кто знает о пластыре для похудения чтонибудь, расскажите! для похудения капсулы ультра эффект новая формула реально похудела: живот втянулся, руки и ноги стали меньше по объ.. Лида капсулы также вы сможете прочитать капсулы для похудения лида купить за..

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>