给定数字N,请找到将这个数字表示为2个或更多个连续自然数之和的方式的数量。
例子:
Input :15
Output :3
15 can be represented as:
1+2+3+4+5
4+5+6
7+8
Input :10
Output :1
10 can only be represented as:
1+2+3+4
想法是将N表示为长度为L + 1的序列,如下所示:
N = a +(a + 1)+(a + 2)+ .. +(a + L)
=> N =(L + 1)* a +(L *(L + 1))/ 2
=>一个=(NL *(L + 1)/ 2)/(L + 1)
我们将L的值替换为从1到L *(L + 1)/ 2
C/C++
// C++ program to count number of ways to express
// N as sum of consecutive numbers.
#include
using namespace std;
long int countConsecutive(long int N)
{
// constraint on values of L gives us the
// time Complexity as O(N^0.5)
long int count = 0;
for (long int L = 1; L * (L + 1) < 2 * N; L++)
{
float a = (1.0 * N-(L * (L + 1)) / 2) / (L + 1);
if (a-(int)a == 0.0)
count++;
}
return count;
}
// Driver Code
int main()
{
long int N = 15;
cout << countConsecutive(N) << endl;
N = 10;
cout << countConsecutive(N) << endl;
return 0;
}
Java
// A Java program to count number of ways
// to express N as sum of consecutive numbers.
public class SumConsecutiveNumber
{
// Utility method to compute number of ways
// in which N can be represented as sum of
// consecutive number
static int countConsecutive(int N)
{
// constraint on values of L gives us the
// time Complexity as O(N^0.5)
int count = 0;
for (int L = 1; L * (L + 1) < 2 * N; L++)
{
float a = (float) ((1.0 * N-(L * (L + 1)) / 2) / (L + 1));
if (a-(int)a == 0.0)
count++;
}
return count;
}
// Driver code to test above function
public static void main(String[] args) {
int N = 15;
System.out.println(countConsecutive(N));
N = 10;
System.out.println(countConsecutive(N));
}
}
// This code is contributed by Sumit Ghosh
Python
# Python program to count number of ways to
# express N as sum of consecutive numbers.
def countConsecutive(N):
# constraint on values of L gives us the
# time Complexity as O(N^0.5)
count = 0
L = 1
while( L * (L + 1) < 2 * N):
a = (1.0 * N - (L * (L + 1) ) / 2) / (L + 1)
if (a - int(a) == 0.0):
count += 1
L += 1
return count
# Driver code
N = 15
print countConsecutive(N)
N = 10
print countConsecutive(N)
# This code is contributed by Sachin Bisht
C#
// A C# program to count number of
// ways to express N as sum of
// consecutive numbers.
using System;
public class GFG {
// Utility method to compute
// number of ways in which N
// can be represented as sum
// of consecutive number
static int countConsecutive(int N)
{
// constraint on values of L
// gives us the time
// Complexity as O(N^0.5)
int count = 0;
for (int L = 1; L * (L + 1)
< 2 * N; L++)
{
float a = (float) ((1.0
* N-(L * (L + 1))
/ 2) / (L + 1));
if (a - (int)a == 0.0)
count++;
}
return count;
}
// Driver code to test above
// function
public static void Main()
{
int N = 15;
Console.WriteLine(
countConsecutive(N));
N = 10;
Console.Write(
countConsecutive(N));
}
}
// This code is contributed by
// nitin mittal.
PHP
输出:
3
1
由于for循环中的条件,该程序的时间复杂度为O(N ^ 0.5)。