מספר קרול
נסה את זה ב-GfG Practice
#practiceLinkDiv { display: none !חשוב; }
#practiceLinkDiv { display: none !חשוב; } מספר קרול הוא מספר שלם של הצורה 4 נ - 2 (n+1) - 1. נוסחה מקבילה היא (2 נ -1) 2 - 2.
נכס מעניין:
עבור n > 2 הייצוג הבינארי של מספר קרול ה-n הוא n-2 אחד ברציפות של אפס בודד באמצע ו-n + 1 אחד רצוף נוסף. דוגמה n = 4 קרול מספר הוא 223 ובינארי של 223 הוא 11011111 כאן n-2 = 4-2 = 2 רצופות בהתחלה ואז יחיד 0 באמצע ואז n + 1 = 4 + 1 = 5 רצופות אחריו.
בהינתן מספר n המשימה היא למצוא את מספר הקרול ה-n. מספרי השירה הראשונים הם -1 7 47 223 959... וכו'.
דוגמאות:
Input : n = 2 Output: 7 Input : n = 4 Output: 223Recommended 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: O(log n) עבור פונקציית pow
מרחב עזר: O(1)