📜  大于p的最小三角数

📅  最后修改于: 2021-04-29 13:28:31             🧑  作者: Mango

给定n个桶,每个桶的编号从1到n,并且其中的花朵等于三角数。您必须从中挑出“ p”朵花后再选择剩下最少花的桶。

第一个存储桶仅包含1个花,第二个存储桶包含3个花,第三个存储桶包含6个花,依此类推,依次为n(n + 1)/ 2。
例子 :

Input : p = 4
Output : bucket 3 
Explanation :
Buckets with flowers : 1 3 6 10 ....
So, bucket 3 is left with only two flowers after 
selecting p flowers from it which is minimum.

Input : p = 10
Output : bucket 4
Explanation :
Bucket with flowers : 1 3 6 10 15 ...
So, selecting 10 flowers from 4th bucket leave
it with 0 flowers.

方法 :
观察不同情况的输入/输出,可以使用以下公式计算存储桶数:

n = ceil( (sqrt(8*p+1)-1)/2 ) ;

它是如何工作的?
我们需要比n *(n + 1)/ 2> = p更小的n
因此,我们需要找到方程n 2 + n – 2 * p> = 0的根。
通过应用这里讨论的公式,我们得到n = ceil((sqrt(8 * p + 1)-1)/ 2)

C++
// CPP code to find the bucket to choose
// for picking flowers out of it
#include
using namespace std;
 
int findBucketNo(int p)
{
   return ceil( ( sqrt( 8*p + 1 ) -1 ) / 2 ) ;
}
 
// Driver code
int main()
{
  int p = 10 ;   
  cout << findBucketNo(p);
  return 0;
}


Java
//Java code to find the bucket to choose
// for picking flowers out of it
import java.lang.System.*;
 
class GFG {
     
    static int findBucketNo(int p)
    {
        return (int)Math.ceil((
        Math.sqrt( 8*p + 1 ) -1 ) / 2 ) ;
    }
     
    // Driver code
    public static void main(String[] args)
    {
        int p = 10 ;
         
        System.out.println(findBucketNo(p));
    }
}
 
// This code is contributed by
// Smitha Dinesh Semwal


Python 3
# Python 3 code to find the bucket
# to choose for picking flowers
# out of it
import math
 
def findBucketNo(p):
 
    return math.ceil( ( math.sqrt(
               8*p + 1 ) -1 ) / 2 )
 
# Driver code
p = 10
 
print(findBucketNo(p))
 
# This code is contributed by
# Smitha Dinesh Semwal


C#
// C# code to find the bucket to choose
// for picking flowers out of it
using System;
 
class GFG {
     
    static int findBucketNo(int p)
    {
        return (int)Math.Ceiling((
        Math.Sqrt( 8*p + 1 ) -1 ) / 2 );
    }
     
    // Driver code
    static public void Main ()
    {
        int p = 10 ;
        Console.WriteLine(findBucketNo(p));
    }
}
 
// This code is contributed by Ajit.


PHP


Javascript


输出 :
4

时间复杂度:O(1)