写一个递归函数threeplustwo,它接受参数(n),将所有可被2整除的数字加起来+所有可从范围(1到n-1)整除3的数字。 [英] Write a recursive function threeplustwo that takes argument (n), sums all numbers divisible by 2 + all numbers divisible by 3 from range(1 to n-1).
问题描述
这是一个模型答案代码(我不明白)
this is a model answer code (which I don't understand )
int threePlusTwo (int n)
{
if (n <= 2)
return 0;
if (n == 3)
return 2;
int twoSum = (n - 1) % 2 == 0? (n - 1): 0;
int threeSum = (n - 1) % 3 == 0? (n - 1): 0;
return twoSum + threeSum + threePlusTwo(n - 1);
}
我的尝试:
What I have tried:
#include<stdio.h>
#include<stdlib.h>
int tpt(int n)
{
if(n==1) return 0;
if(n%3==0||n%2==0) return n+tpt(n-1);
return tpt(n-1);
}
我的代码的问题是n> = 6的测试用例因为||它只有6次条件...任何想法如何修改我的代码以通过该测试用例?!
推荐答案
你必须理解文本的含义你的作业并将其翻译成代码:
从范围(1到n-1)转换为:
You must understand the meaning of the text of your homework and tranlate it into code:
"from range (1 to n-1)" translates to:
for( int i = 1; i < n; i++ ) {
//do magic stuff
}
将所有可分为2的数字相加(一些神奇的东西)
"sum all numbers divisable by 2" (some magic stuff)
if( (i %2) == 0) ) // % is modulo operator
{
sum = summ + n;
}
提示:对3部分使用else if语句。
祝你好运与你的作业。并编写一些测试来检查正确的结果。
Tip: use a else if statement for the 3 part.
Good luck with your homeworks. And write some tests for checking the correct results.
请记住,你必须考虑(n-1)
as上限。让我们看一下如何解释模型程序
Keep in mind you have to consider(n-1)
as upper limit. Let's see how the model program could be intepreted
if (n <= 2)
return 0;
这是微不足道的,因为 1
不能被 2
或<整除code> 3 。
This is trivial, since 1
is not divisible by 2
or 3
.
if (n == 3)
return 2;
这也是微不足道的,因为在 1,2
序列中,只有 2
可以整除。
This is trivial too, since in the 1,2
sequence, there is only 2
which is divisible.
int twoSum = (n - 1) % 2 == 0? (n - 1): 0;
这意味着
This means
int twoSum;
if ( (n-1) % 2 == 0)
twoSum = (n-1);
else
twoSum = 0;
即if(n-1)可被 2
整除,然后保留它以便将其添加到总和。
解释
That is "if (n-1) is divisible by 2
then keep it in order to add it to the sum".
The intepretation of
int threeSum = (n - 1) % 3 == 0? (n - 1): 0;
类似。
is similar.
return twoSum + threeSum + threePlusTwo(n - 1);
这样可以添加两倍于 2
和<$ c $的数字c> 3 (请注意问题标题中的这一要求并不明显。)
This makes the trick of adding two times a number which divisible both by 2
and 3
(please note such a requirement is not obvious from the question title).
这篇关于写一个递归函数threeplustwo,它接受参数(n),将所有可被2整除的数字加起来+所有可从范围(1到n-1)整除3的数字。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!