Carol Número
Experimente no GfG Practice
#practiceLinkDiv { display: nenhum! Importante; }
#practiceLinkDiv { display: nenhum! Importante; } Um número Carol é um número inteiro da forma 4 n - 2 (n+1) - 1. Uma fórmula equivalente é (2 n -1) 2 - 2.
Uma propriedade interessante:
Para n> 2, a representação binária do n-ésimo número Carol é n-2 consecutivos, um único zero no meio e n + 1 mais consecutivos. Exemplo n = 4 o número da canção é 223 e o binário de 223 é 11011111 aqui n-2 = 4-2 = 2 consecutivos no início, então único 0 no meio e então n + 1 = 4 + 1 = 5 consecutivos depois dele.
Dado um número n, a tarefa é encontrar o enésimo número Carol. Os primeiros números de canções de natal são -1 7 47 223 959... etc.
Exemplos:
Input : n = 2 Output: 7 Input : n = 4 Output: 223Recommended Practice Carol Números Experimente! 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>
Saída :
223
Complexidade de tempo y: O (log n) para função pow
Espaço Auxiliar: O(1)