Prime numbers program

后端 未结 14 1496
无人及你
无人及你 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 01:11
    for(int currentInt=2; currentInt<=1000000; currentInt++) 
    
    {check = false;  // Basically the idea for this for loop is to run checks against integers. This is the main for loop in this program. I re initialize check to false ( check is a bool declared above this. )
    
    for( int arrayPrime=0; arrayPrime<currentPrime; arrayPrime++) // This for loop is used for checking the currentInt against previously found primes which are stored in the num array.
    
    { c=num[arrayPrime];
            if ((currentInt%c)==0) { check = true;// second filter based on previous recorded primes in array
                    break;}  // this is the check. I check the number against every stored value in the num array. If it's divisible by any of them, then bool check is set to true.
    
    
    if ( currentInt == 2)
    { check = false; } // since i preset num[0] = 2 i make an exception for the number 2.
    
    if (!check)
    {
    e=a;
    if(currentPrime <= 100){
    num[currentPrime]= currentInt;} // This if uses check to see if the currentInt is a prime. 
    
    currentPrime = currentPrime+1;} // increases the value of currentPrime ( previously b ) by one if !check.
    
    if(currentPrime==prime)
    {
    write<<e<<endl;
    break;}           // if currentPrime == prime then write the currentInt into a txt file and break loop, ending the program.
    

    Thanks for the advice polythinker =)

    0 讨论(0)
  • 2021-01-07 01:13

    From what I know, in C/C++ int is a 16bit type so you cannot fit 1 million in it (limit is 2^16=32k). Try and declare "a" as long

    I think the C standard says that int is at least as large as short and at most as large as long.

    In practice int is 4 bytes, so it can hold numbers between -2^31 and 2^31-1.

    0 讨论(0)
提交回复
热议问题