英文:
Add the multiples of 3 and 5 till n
问题
这是我的第一个查询,希望能得到恰当的回答。这是来自HackerRank网站的一个问题。
问题:将3和5的倍数相加,直到"N"为止。
示例输入0:
100
示例输出0:
2318
我的代码:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int sum=0,j=3,k=5;
for(int a0 = 0; a0 < t; a0++)
{
int n = in.nextInt();
while(j<n)
{
sum=sum+j;
j+=3;
}
while(k<n)
{
sum=sum+k;
k+=5;
}
System.out.println(sum);
sum=0;
}
}
}
这段代码给我输出错误的结果。请解决这个问题。
英文:
This is my first query, hope I am answered appropriately. This is a question from hackerrank website.
Question: Add the multiples of 3 and 5 together uptill "N"
Sample Input 0
100
Sample Output 0
2318
My Code:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int sum=0,j=3,k=5;
for(int a0 = 0; a0 < t; a0++)
{
int n = in.nextInt();
while(j<n)
{
sum=sum+j;
j+=3;
}
while(k<n)
{
sum=sum+k;
k+=5;
}
System.out.println(sum);
sum=0;
}
}
}
This code is giving me a wrong output. Please attend to this problem.
答案1
得分: 1
为了判断一个数字是否是另一个数字的倍数,最简单的方法是将一个数字除以另一个数字并检查余数。您从未这样做过。
我建议这样做:
import java.util.Scanner;
public class Main {
private static final int THREE = 3;
private static final int FIVE = 5;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int sum=0;
for(int a0 = 0; a0 <= t; a0++)
{
if (a0 % THREE == 0 || a0 % FIVE == 0) {
sum += a0;
}
}
System.out.println(sum);
}
}
英文:
To know if a number is a multiple of another, the easiest way is to divide one by the other and check the modulo. You never do that.
I would suggest something like that :
import java.util.Scanner;
public class Main {
private static final int THREE = 3;
private static final int FIVE = 5;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int sum=0;
for(int a0 = 0; a0 <= t; a0++)
{
if (a0 % THREE == 0 || a0 % FIVE == 0) {
sum += a0;
}
}
System.out.println(sum);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论