递归题:(在有inc()和dec()的情况下)不允许用==以外的运算符和for()/while()计算两个数的乘积

Jimmy Carlson posted @ 2017年11月29日 09:28 in OI / CS with tags python , 869 阅读
2019 JCarlson Works All Rights Reserved

今天这个题目有点意思。

题目要求:计算两个数的乘积

限制1:不允许使用==以外的运算符(除了定义inc()和dec()外)

限制2:不允许使用for和while

限制3:不允许导入各种奇怪的函数

 

这题就用递归做啦~

这道题目恶心之处在于不允许用==以外的运算符导致我想了5分钟很久。嗯。

 

首先还是定义inc和dec。

def inc(n):
	return n+1;
	
def dec(n):
	return n-1;

然后定义add(a,b)。效果是计算a+b的值。这个就用递归把b拆成0+1+1+...+1(一共b个1)就行了。

def add(a,b):
	if (b == 0):
		return a;
	else:
		return inc(add(a,dec(b)));

之后就定义一个mul(a,b)。效果计算a*b的值。和上面一个原理一样,把a*b拆成0+a+a+...+a(一共b个a)就行了。

代码见下。

def mul(a,b):
	if (b == 0):
		return 0;
	else:
		return add(a,mul(a,dec(b)));

最后在main里把I/O处理掉就结束。

print(mul(int(input()),int(input())));

 

(未完待续?)

吐槽一句——这是哪个老师出的这种神奇题目 就算练递归也不需要这么练吧= =

2019 JCarlson Works All Rights Reserved
Avatar_small
absi2011 说:
2017年12月04日 15:42

日常巡视JCW的blog
你可以尝试做一下 a+b problem 全程禁止使用加号和减号
甚至我们可以考虑更进一步,我们禁止你用乘号和除号,再加个if也可以

Avatar_small
Ebtedayee Result 说:
2022年8月30日 00:45

Government of the People’s Republic of Bangladesh, Directorate of Primary Education (DPE), is going to announce PSC Result 2022 in student wide on 30th December 2022 for all divisional Grade 5 exam result with Ebtedayee Result 2022 for annual final terminal examinations, The Primary School Certificate Examination Result 2022 will be announced for both of General and Madhrsah students in division wise to all education board known as Prathomik Somaponi Result 2022. Ebtedayee ResultThe DPE has successfully conducted the class 5th grade PSC and Ebtedayee Examination tests from 17th to 24th November 2022 under all education boards of Dhaka, Chittagong, Comilla, Rajshahi, Sylhet, Barisal, Jessore, Dinajpur and Madrasah Board, and the DPE Grade-5 exams are successfully conducted at all 7,194 centers across the country.

Avatar_small
Rajasthan Board Mode 说:
2022年10月03日 17:00

Rajasthan Board Model Paper 2023 Pdf Download for School Education Ajmer & Jaipur Board Sample Model Question Paper for Class 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 & 12 Standard Theory, Objective (MCQ) and Bit Questions for Hindi Medium, English Medium, Urdu Medium and others. New Exam Scheme orRajasthan Board Model Paper Question Pattern for Sammittive Assignment Exams (SA1 & SA2): Very Long Answer (VLA), Long Answer (LA), Small Answer (SA), Very Small Answer (VSA), Single Answer, Multiple Choice and etc.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter