UVA138---StreetNumber

问题描述:

A computer programmer lives in a street with houses numbered consecutively (from 1) down one side of the street. Every evening she walks her dog by leaving her house and randomly turning left or right and walking to the end of the street and back. One night she adds up the street numbers of the houses she passes (excluding her own). The next time she walks the other way she repeats this and finds, to her astonishment, that the two sums are the same. Although this is determined in part by her house number and in part by the number of houses in the street, she nevertheless feels that this is a desirable property for her house to have and decides that all her subsequent houses should exhibit it.

Write a program to find pairs of numbers that satisfy this condition. To start your list the first two pairs are: (house number, last number):

         6         8
        35        49

Input and Output

There is no input for this program. Output will consist of 10 lines each containing a pair of numbers, each printed right justified in a field of width 10 (as shown above).


本题开始的时候没看懂,看得时候我想,可以随机往左右转弯,是怎么转的啊,转的时候还要计数,是不是街道的左右两边都可以计数啊。这样想程序就没法写了。看了一下提示:http://blog.csdn.net/goomaple/article/details/8545440其中的“给你两个数m、n,使得m、n之间的数之和与1~m之间的数之和相等”,让我明白了,原来是从家里出来是随机选择方向,之后就一路走到底,边走边计数,然后就明白了。我写的程序如下:

#include<iostream>
#include<iomanip>
#include<cstdlib>
using namespace std;

int main()
{
	int cnt=0;
	for(int i=1;cnt<10;++i)
	{
		for(int j=i+1;2*i*i>=j*(j+1);++j)
		{
			if(2*i*i==j*(j+1))
			{
				++cnt;
				cout<<setw(10)<<setiosflags(ios::right)<<i<<setw(10)<<setiosflags(ios::right)<<j<<endl;
				break;
			}
		}
	}
	system("pause");
	return 0;
}

与他给的答案比较,迭代的次数多了,可以化简

另一个代码粘贴如下:

#include<stdio.h>  
#include<math.h>  
int main()  
{  
    freopen("out.txt", "w", stdout);  
    long long _mid;  
    double mid;  
    for(int i=6; i<100000000; i++)  
    {  
        mid = (double)i*(i+1);  
        mid /= 2;  
        mid = sqrt(mid);  
        _mid = mid;// 取mid的整数部分  
        if(fabs(mid-(double)_mid) < 1e-10)
            printf("printf(\"%%10d%%10d\\n\", %I64d, %d);\n", _mid, i);  
    }  
    return 0;  
}  

这个简洁多了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值