📌  相关文章
📜  检查数字是否可以表示为连续数字的总和

📅  最后修改于: 2021-05-25 10:26:34             🧑  作者: Mango

给定数字n,任务是检查它是否可以表示为两个或多个连续数字的总和。
例子:

Input  : n = 10 
Output : true
It can be expressed as sum of two consecutive
numbers 1 + 2 + 3 + 4.

Input  : n = 16  
Output : false
It cannot be expressed as sum of two consecutive
numbers.

Input  : n = 5  
Output : true
2 + 3 = 5

有一个直接而快速的方法可以解决此问题。如果数字是2的幂,则不能将其表示为连续数字的总和,否则为Yes。
这个想法基于以下两个事实。
1)任何两个连续数字的总和是奇数,因为其中一个必须是偶数而另一个是奇数。
2)2 n = 2 n-1 + 2 n-1
如果我们仔细研究1)和2),我们可以得到事实的直觉。
以下是上述想法的实现。

C++
// C++ program to check if a number can
// be expressed as sum of consecutive numbers
#include
using namespace std;
 
// This function returns true if n can be
// expressed sum of consecutive.
bool canBeSumofConsec(unsigned int n)
{
    // We basically return true if n is a
    // power of two
    return ((n&(n-1)) && n);
}
 
// Driver code
int main()
{
    unsigned int n = 15;
    canBeSumofConsec(n)? cout << "true" :
                         cout << "false";
    return 0;
}


Java
// Java program to check if a number can
// be expressed as sum of consecutive numbers
 
class Test
{
    // This function returns true if n can be
    // expressed sum of consecutive.
    static boolean canBeSumofConsec(int n)
    {
        // We basically return true if n is a
        // power of two
        return (((n&(n-1))!=0) && n!=0);
    }
     
    // Driver method
    public static void main(String[] args)
    {
        int n = 15;
        System.out.println(canBeSumofConsec(n) ? "true" : "false");
    }
}


Python3
# Python 3 program to check if a number can
# be expressed as sum of consecutive numbers
 
 
# This function returns true if n
# can be expressed sum of consecutive.
def canBeSumofConsec(n) :
 
    # We basically return true if n is a
    # power of two
    return ((n&(n-1)) and n)
 
 
# Driver code
n = 15
if(canBeSumofConsec(n)) :
    print("true")
else :
    print("false")
     
# This code is contributed by Nikita Tiwari.


C#
// C# program to check if a number can be
// expressed as sum of consecutive numbers
using System;
 
class Test
{
    // This function returns true if n
    // can be expressed sum of consecutive.
    static bool canBeSumofConsec(int n)
    {
        // We basically return true if n is a
        // power of two
        return (((n & (n - 1)) != 0) && n != 0);
    }
     
    // Driver Code
    public static void Main()
    {
        int n = 15;
        Console.Write(canBeSumofConsec(n) ? "True" : "False");
    }
}
 
// This code is contributed by Nitin Mittal.


PHP


Javascript


输出:

True