Home > front end >  How to return last prime number from interval with while loop and ifs in C#
How to return last prime number from interval with while loop and ifs in C#

Time:02-26

I'm trying to display last prime number for a given interval. For example:

  1. if n is 10 last prime nubmer is 7

  2. if n is 11 last prime nubmer is 11

  3. if n is 14 last prime number is 13

  4. etc...

     public static uint LastPrimeNumberInInterval(uint n)
     {
         uint result = 0;
         uint i = 2;
    
         while (i <= n)
         {
             bool b = false;
    
             while (i <= n / 2)
             {
                 if (n % i == 0)
                 {
                     b = true;
                     break;
                 }
    
                 i  ;
             }
    
             if (!b)
             {
                 result = i;
             }
    
             i  ;
         }
    
         return result;
     }
    

but I'm stuck on displaying only correct answer when n is prime number. Can someone point out where is my fault?

CodePudding user response:

You need to use a different variable in your nested loop and reset it for each number being checked.

public static uint LastPrimeNumberInInterval(uint n)
 {
     uint result = 0;
     uint i = 2;

 while (i <= n)
 {
     bool b = false;
     uint j = 2;

     while (j <= n / 2)
     {
         if (n % j == 0)
         {
             b = true;
             break;
         }

         j  ;
     }

     if (!b)
     {
         result = i;
     }

     i  ;
 }

 return result;


}

CodePudding user response:

Based on your method:

public static uint LastPrimeNumberInInterval(uint n)
 {
     uint result = 0;
     uint i = 2;
     
     if (n < 2) return result;

     while (i <= n)
     {
         bool b = false;

         uint j = 2;
         while (j <= n / 2)
         {
             if (i % j == 0)
             {
                 b = true;
                 break;
             }

             j  ;
         }

         if (!b)
         {
             result = i;
         }

         i  ;
     }

     return result;
 }
  • Related