Odd numbers in N-th row of Pascal’s Triangle
Last Updated :
15 Jun, 2022
Given N, the row number of Pascal’s triangle(row starting from 0). Find the count of odd numbers in the N-th row of Pascal’s Triangle.
Prerequisite: Pascal’s Triangle | Count number of 1’s in binary representation of N
Examples:
Input : 11
Output : 8
Input : 20
Output : 4
Approach: It appears the answer is always a power of 2. In fact, the following theorem exists:
THEOREM: The number of odd entries in row N of Pascal’s Triangle is 2 raised to the number of 1’s in the binary expansion of N.
Example: Since 83 = 64 + 16 + 2 + 1 has binary expansion (1010011), then row 83 has pow(2, 4) = 16 odd numbers.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std ;
int countSetBits( int n)
{
unsigned int count = 0;
while (n)
{
count += n & 1;
n >>= 1;
}
return count;
}
int countOfOddsPascal( int n)
{
int c = countSetBits(n);
return pow (2, c);
}
int main()
{
int n = 20;
cout << countOfOddsPascal(n) ;
return 0;
}
|
Java
import java.io.*;
class GFG {
static int countSetBits( int n)
{
long count = 0 ;
while (n > 0 )
{
count += n & 1 ;
n >>= 1 ;
}
return ( int )count;
}
static int countOfOddsPascal( int n)
{
int c = countSetBits(n);
return ( int )Math.pow( 2 , c);
}
public static void main (String[] args)
{
int n = 20 ;
System.out.println(
countOfOddsPascal(n));
}
}
|
Python3
def countSetBits(n):
count = 0
while n:
count + = n & 1
n >> = 1
return count
def countOfOddPascal(n):
c = countSetBits(n)
return pow ( 2 , c)
n = 20
print (countOfOddPascal(n))
|
C#
using System;
class GFG {
static int countSetBits( int n)
{
int count = 0;
while (n > 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
static int countOfOddsPascal( int n)
{
int c = countSetBits(n);
return ( int )Math.Pow(2, c);
}
public static void Main ()
{
int n = 20;
Console.WriteLine(
countOfOddsPascal(n)) ;
}
}
|
PHP
<?php
function countSetBits( $n )
{
$count = 0;
while ( $n )
{
$count += $n & 1;
$n >>= 1;
}
return $count ;
}
function countOfOddsPascal( $n )
{
$c = countSetBits( $n );
return pow(2, $c );
}
$n = 20;
echo countOfOddsPascal( $n ) ;
?>
|
Javascript
<script>
function countSetBits(n)
{
let count = 0;
while (n > 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
function countOfOddsPascal(n)
{
let c = countSetBits(n);
return Math.pow(2, c);
}
let n = 20;
document.write(countOfOddsPascal(n)) ;
</script>
|
Time Complexity: O(L), where L is the length of a binary representation of a given N.
Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...