Determining if a number is prime

后端 未结 20 1340
悲哀的现实
悲哀的现实 2020-11-30 03:05

I have perused a lot of code on this topic, but most of them produce the numbers that are prime all the way up to the input number. However, I need code which only checks w

20条回答
  •  庸人自扰
    2020-11-30 03:24

    Use mathematics first find square root of number then start loop till the number ends which you get after square rooting. check for each value whether the given number is divisible by the iterating value .if any value divides the given number then it is not a prime number otherwise prime. Here is the code

     bool is_Prime(int n)
     {
    
       int square_root = sqrt(n); // use math.h
       int toggle = 1;
       for(int i = 2; i <= square_root; i++)
       {
         if(n%i==0)
         { 
            toggle = 0;
            break;
         }
       }
    
       if(toggle)
         return true;
       else
         return false;
    
     } 
    

提交回复
热议问题