Open In App

Carol Number

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A Carol number is an integer of the form 4n – 2(n+1) – 1. An equivalent formula is (2n-1)2 – 2.
An Interesting Property : 
For n > 2, the binary representation of the n-th Carol number is n-2 consecutive one’s, a single zero in the middle, and n + 1 more consecutive one’s. Example, n = 4 carol number is 223 and binary of 223 is 11011111, here n-2 = 4-2 = 2 consecutive ones in starting then single 0 in middle and then n + 1 = 4 + 1 = 5 consecutive ones after it.
Given a number n, the task is to find the nth Carol Number. First, few carol numbers are -1, 7, 47, 223, 959… etc.

Examples : 

Input : n = 2
Output: 7

Input : n = 4
Output: 223
Recommended Practice

C++




// C++ program to find n'th Carol number
#include <bits/stdc++.h>
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
// 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>


Output : 

223

Time complexity: O(log n) , for pow function

Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads