キャロル番号

キャロル番号
GfG Practice で試してみる #practiceLinkDiv { 表示: なし !重要; }

キャロル番号は 4 の形式の整数です。 n - 2 (n+1) - 1. 同等の式は (2 n -1) 2 - 2.
興味深い物件: 
n > 2 の場合、n 番目のキャロル数の 2 進数表現は、n-2 個の連続する 1 が中央に 1 つあり、さらに n + 1 個の連続する 1 になります。例 n = 4 のキャロル番号は 223 で、223 の 2 進数は 11011111 です。ここで、n-2 = 4-2 = 先頭に 2 つの連続する 1 があり、中央に 1 つの 0 があり、その後に n + 1 = 4 + 1 = 5 つの連続する 1 が続きます。
数値 n が与えられると、タスクは n 番目のキャロル番号を見つけることです。最初のいくつかのキャロル番号は -1 7 47 223 959... などです。

例:  

Input : n = 2 Output: 7 Input : n = 4 Output: 223 
Recommended Practice キャロルナンバー 試してみてください! C++
   // C++ program to find n'th Carol number   #include          using     namespace     std  ;   // Function to find n'th carol number   int     carol  (  int     n  )   {      int     result     =     pow  (  2       n  )     -     1  ;      return     result     *     result     -     2  ;   }   // Driver program to ru the case   int     main  ()   {      int     n     =     4  ;      cout      < <     carol  (  n  );      return     0  ;   }   
Python3
   # Python program to find n'th Carol number   def   carol  (  n  ):   # a**b is a ^ b in python   result   =   (  2  **  n  )   -   1   return   result   *   result   -   2   # driver program to run the case   n   =   4   print   (  carol  (  n  ))   
Java
   /* Java program to find n'th Carol number */   class   GFG     {      static     int     carol  (  int     n  )      {      double     tmp     =     Math  .  pow  (  2       n  )     -     1  ;      return     (  int  )  tmp  ;      }      public     static     void     main  (  String  []     args  )      {      int     n     =     4  ;      System  .  out  .  println  (  carol  (  n  ));      }   }   
C#
   /* C# program to find n'th Carol number */   using     System  ;   class     GFG     {      static     int     carol  (  int     n  )      {      int     result     =     (  int  )  Math  .  Pow  (  2       n  )     -     1  ;      return     result     *     result     -     2  ;      }      // Driver code      public     static     void     Main  ()      {      int     n     =     4  ;      Console  .  WriteLine  (  carol  (  n  ));      }   }   // This code is contributed by vt_m.   
PHP
      // PHP program to find   // n'th Carol number   // Function to find   // n'th carol number   function   carol  (  $n  )   {   $result   =   pow  (  2     $n  )   -   1  ;   return   $result   *   $result   -   2  ;   }   // Driver Code   $n   =   4  ;   echo   carol  (  $n  );   // This code is contributed by ajit   ?>   
JavaScript
    <  script  >      /* Javascript program to find n'th Carol number */          function     carol  (  n  )      {      let     result     =     Math  .  pow  (  2       n  )     -     1  ;      return     result     *     result     -     2  ;      }          let     n     =     4  ;      document  .  write  (  carol  (  n  ));        <  /script>   

出力:  

223 

時間の複雑さ y: pow 関数の場合は O(log n)

補助スペース: ○(1)