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

這個簡潔多了

發佈了48 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章