📜  查找三角数的序列号

📅  最后修改于: 2021-06-26 15:24:37             🧑  作者: Mango

给定整数N,则打印给定三角数的序列号。如果该数字不是三角形数字,则打印-1。

例子:

方法:

  1. 由于奇偶数是自然数的和,因此可以概括为二次方程。
C++
// C++ code to print sequence
// number of a triangular number
#include
using namespace std;
 
int main()
{
    int N = 21;
    int A = sqrt(2 * N + 0.25) - 0.5;
    int B = A;
 
    // If N is not tringular number
    if (B != A)
        cout << "-1";
    else
        cout << B;
}
 
// This code is contributed by yatinagg


Java
// Java code to print sequence
// number of a triangular number
import java.util.*;
class GFG{
     
public static void main(String args[])
{
    int N = 21;
    int A = (int)(Math.sqrt(2 * N + 0.25) - 0.5);
    int B = A;
 
    // If N is not tringular number
    if (B != A)
        System.out.print("-1");
    else
        System.out.print(B);
}
}
 
// This code is contributed by Akanksha_Rai


Python3
# Python3 code to print sequence
# number of a triangular number
 
import math
 
N = 21
A = math.sqrt(2 * N + 0.25)-0.5
B = int(A)
 
# if N is not tringular number
if B != A:
    print(-1)
else:
    print(B)


C#
// C# code to print sequence
// number of a triangular number
using System;
class GFG{
     
public static void Main()
{
    int N = 21;
    int A = (int)(Math.Sqrt(2 * N + 0.25) - 0.5);
    int B = A;
 
    // If N is not tringular number
    if (B != A)
        Console.Write("-1");
    else
        Console.Write(B);
}
}
 
// This code is contributed by Code_Mech


Javascript


输出:
6

时间复杂度: O(1)
辅助空间: O(1)