Prime numbers program

后端 未结 14 1501
无人及你
无人及你 2021-01-07 00:27

I\'m currently trying out some questions just to practice my programming skills. ( Not taking it in school or anything yet, self taught ) I came across this problem which re

14条回答
  •  孤城傲影
    2021-01-07 00:49

    There are a two approaches to testing for primality you might want to consider:

    1. The problem domain is small enough that just looping over the numbers until you find the Nth prime would probably be an acceptable solution and take less than a few milliseconds to complete. There are a number of simple optimizations you can make to this approach for example you only need to test to see if it's divisible by 2 once and then you only have to check against the odd numbers and you only have to check numbers less than or equal to the aquare root of the number being tested.
    2. The Sieve of Eratosthenes is very effective and easy to implement and incredibly light on the math end of things.

    As for why you code is crashing I suspect changing the line that reads

    for( int d=0; d<=b; d++) 
    

    to

    for( int d=0; d

    will fix the problem because you are trying to read from a potentially uninitialized element of the array which probably contains garbage.

提交回复
热议问题