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; }