程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Triangular numbers

Triangular numbers

編輯:C++入門知識

Triangular numbers
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. . You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number).

Your task is to find out if a given integer is a triangular number.

Input
The first line contains the single number n (1 ≤ n ≤ 500) — the given integer.

Output
If the given integer is a triangular number output YES, otherwise output NO.

Sample test(s)
input
1
output
YES
input
2
output
NO
input
3
output
YES


用一個哈希表存儲哪些是triangular number,滿足這個數字的要求就是這個數能由公式得到。
AC代碼:

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

int p[200000];

int main()
{
    int n,i,x;
    memset(p,0,sizeof(p));
    for(i = 1; i <= 500; i++)
    {
        x = i*(i+1)/2;
        p[x] = 1;
    }
    while(scanf("%d",&n)!=EOF)
    {
        if(p[n] == 1)
        {
            printf("YES\n");
        }
        else
        {
            printf("NO\n");
        }
    }

    return 0;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved