JOJ 1007解题

该博客介绍了如何确定一个正整数是否为三角形数,即是否有形式为1/2 * n * (n+1)的表达式。内容中给出了输入输出格式以及样例输入输出,说明了输入为小于2000的正整数,输出为判断结果及对应的三角形图案(如果是三角形数)。
摘要由CSDN通过智能技术生成

 1007: Triangles


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
3s 8192K 7020 2611 Standard

A triangle can be made up out of dots, like the ones shown below:

The number of dots in each one is called a triangular number. More precisely, a number is said to be triangular if it is of the form ½ n(n+1). The numbers 1, 3, 6, 10, and 15 are all triangular.

Given a number, determine if it is triangular. If it is, draw the corresponding right triangle, if it is not, say so.

Input

A positive integer less than 2000. Each case will be on a separate line. A zero (0) denotes the end of input.

Output

The phrase “<num> is a triangular number.” followed by a right triangle of “*” characters, or the phrase “<num> is not a triangular number.” The triangle should be oriented with the hypotenuse on the right and the right angle in the lower left.

Sample Input

3
4
6
0

Sample Output

3 is a triangular number.
*
**
4 is not a triangular number.
6 is a triangular number.
*
**
***
代码如下:
#include <iostream>
#include <queue>
#include <cmath>
using namespace std;

bool isTriangle(int n)
{
    n = 2*n;
    int srt = (int)sqrt(n);
    if (srt * (srt + 1) == n)
        return  true;
    return false;
}

void printTriangle(int n)
{
    for (int i = 1 ; i <= n; i ++)
    {
        for(int j = 1; j <= i ; j ++)
            cout<<"*";
        cout<<endl;
    }
}
int main()
{
    queue<int> input;
    int a;
    while (cin>>a && a!=0)
    {
        input.push(a);
    }
    while (!input.empty())
    {
        if(isTriangle(input.front()))
        {
            cout << input.front() << " is a triangular number."<<endl;
            printTriangle((int)sqrt(input.front()*2));
        }
        else
        {
            cout << input.front() << " is not a triangular number."<<endl;
        }
        input.pop();
    }
    return 0;
}
主要解题思路:
如果一个数是三角数,那么一定有N= 1/2*n(n+1),因此就有:2*N = n*(n + 1);
可以推出:n < sqrt(n*(n+1)) < n + 1,所以我们可以得出:n = (int)sqrt( n*(n+1))(注:截取整数部分,这个结果一定不是一个整数)
然后再验证是否有:n*(n + 1) == 2*N,如果是,那么N就是三角数,否则就不是三角数。
知道了这些就不难理解上面的解题思路了!!
有不妥之请留言,共同探讨,共同进步!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值