所以我正在做Project Euler挑战,我被困在第一个挑战中,我使用Java作为pl。例如,如果我们必须列出10以下的所有自然数,它们是3或5的倍数,我们得到3,5,6和9,这些倍数的总和是23。我们必须求出N以下3或5的所有倍数的总和。
我的代码可以在Eclipse上运行,但是我得到“不错的尝试,但是您没有通过这个测试用例”。使用stdout :没有响应,当我提交代码时,我在所有测试用例上都得到了错误的答案,下面是代码:
public class Solution {
public static void main(String[] args) {
for (int j = 0; j < args.length; j++) {
int N = Integer.parseInt(args[j]);
if (Somme(N) != 0) {
System.out.println(Somme(N));
}
}
}
public static int Somme(int Nn) {
int s = 0;
for (int i = 0; i < Nn; i++) {
if (((i % 3) == 0) || ((i % 5) == 0)
&& !(((i % 3) == 0) && ((i % 5) == 0))) {
s = s + i;
}
}
return (s);
}
}更新:所以,我看了更多,结果发现这是应该怎么做的:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int Nbr = Integer.parseInt(line);
for(int j=0; j<Nbr;j++)
{
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
String line2 = br2.readLine();
String[] numbers = new String[Nbr];
numbers[j]= line2;
System.out.println(Somme(Long.parseLong(numbers[j])));
}
}
public static long Somme(long Nn) {
long s = 0;
for (int i = 0; i < Nn; i++) {
if (((i % 3) == 0) || ((i % 5) == 0)) {
s = s + i;
}
}
return (s);
}}
现在唯一的问题是,我希望它能够读取所有的数字,然后显示总和,现在它读取一个数字,并在后面显示总和,有什么想法吗?
发布于 2015-07-02 07:25:31
您正在跳过一些不应该跳过的数字。
if (((i % 3) == 0) || ((i % 5) == 0)
&& !(((i % 3) == 0) && ((i % 5) == 0)))这条声明说:i必须能被3或5整除,而不能被3和5整除。重述:i必须能被3或5整除,但不能同时被这两个整除。只需删除第二行,它就可以工作了。
https://stackoverflow.com/questions/31172993
复制相似问题