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

Codeforces 328A-IQ Test(數列)

編輯:C++入門知識

Codeforces 328A-IQ Test(數列)


A. IQ Test time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output

Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.

Arithmetic progression is a sequence a1, a1?+?d, a1?+?2d, ..., a1?+?(n?-?1)d, where a1 and d are any numbers.

Geometric progression is a sequence b1, b2?=?b1q, ..., bn?=?bn?-?1q, where b1?≠?0, q?≠?0, q?≠?1.

Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer.

Input

The first line contains exactly four integer numbers between 1 and 1000, inclusively.

Output

Print the required number. If the given sequence is arithmetic progression, print the next progression element. Similarly, if the given sequence is geometric progression, print the next progression element.

Print 42 if the given sequence is not an arithmetic or geometric progression.

Sample test(s) input
836 624 412 200
output
-12
input
1 334 667 1000
output
1333
題意: 給4個數,判斷是否為等差或等比數列(等比數列的定義與高中相同但是公比不能為1,公比為1其實就是等差數列了。。)如果是等比或等差數列,輸入其下一項,否則輸入“42”。如果下一項不是整數也輸出“42”
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int INF=0x3f3f3f3f;
#define LL long long
double a[5];
double is_dc()
{
	for(int i=1;i<3;i++)
		if(a[i]-a[i-1]!=a[i+1]-a[i])
		return INF;
	return a[1]-a[0];
}
double is_db()
{
	for(int i=1;i<3;i++)
		if(a[i]/a[i-1]!=a[i+1]/a[i])
		return INF;
	return a[1]/a[0];
}
int main()
{
	while(scanf("%lf%lf%lf%lf",a,a+1,a+2,a+3)!=EOF)
	{
		if(is_dc()!=INF)
		{
			printf("%.0lf\n",a[3]+is_dc());
		}
		else if(is_db()!=INF)
		{
			double t=is_db()*a[3];
			if(t-floor(t)==0)
			{
				printf("%.0lf\n",t);
			}
			else
				puts("42");
		}
		else
			puts("42");
	}
	return 0;
}

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