Check if a number can be expressed as a sum of consecutive numbers
PROBLEM :
Given a number n, the task is to check whether it can be expressed as a sum of two or more consecutive numbers or not.
Examples:
Input : n = 10
Output : 1
It can be expressed as sum of two consecutive
numbers 1 + 2 + 3 + 4.
Input : n = 16
Output : 0
It cannot be expressed as sum of two consecutive
numbers.
Input : n = 5
Output : 1
2 + 3 = 5
Input:
The first line contains 'T' denoting the number of test cases. Then follows description of test cases.
Each test case contains a single positive integer n.
Output:
Print "1" if number can be expressed as sum of consecutives else "0". (Without the double quotes)
Constraints:
1<=T<=200
0<=N<=10^18
Example:
Input :
2
4
5
Output :
0
1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
bool SumConsecutives(long long ) ;
int main()
{
int t ;
cin>>t ;
while(t--){
long long no ;
cin>>no ;
if(SumConsecutives(no))
cout<<1 ;
else
cout<<0 ;
cout<<endl ;
}
return 0;
}
bool SumConsecutives(long long no){
if(no&&(no&(no-1)))
return true ;
return false ;
}
---------------------------------------------------------------------------------
Given a number n, the task is to check whether it can be expressed as a sum of two or more consecutive numbers or not.
Examples:
Input : n = 10
Output : 1
It can be expressed as sum of two consecutive
numbers 1 + 2 + 3 + 4.
Input : n = 16
Output : 0
It cannot be expressed as sum of two consecutive
numbers.
Input : n = 5
Output : 1
2 + 3 = 5
Input:
The first line contains 'T' denoting the number of test cases. Then follows description of test cases.
Each test case contains a single positive integer n.
Output:
Print "1" if number can be expressed as sum of consecutives else "0". (Without the double quotes)
Constraints:
1<=T<=200
0<=N<=10^18
Example:
Input :
2
4
5
Output :
0
1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
bool SumConsecutives(long long ) ;
int main()
{
int t ;
cin>>t ;
while(t--){
long long no ;
cin>>no ;
if(SumConsecutives(no))
cout<<1 ;
else
cout<<0 ;
cout<<endl ;
}
return 0;
}
bool SumConsecutives(long long no){
if(no&&(no&(no-1)))
return true ;
return false ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment