将3和5的倍数相加直至n。

huangapple go评论109阅读模式
英文:

Add the multiples of 3 and 5 till n

问题

这是我的第一个查询,希望能得到恰当的回答。这是来自HackerRank网站的一个问题。

问题:将3和5的倍数相加,直到"N"为止。

示例输入0:
100

示例输出0:
2318

我的代码:

  1. import java.io.*;
  2. import java.util.*;
  3. public class Solution {
  4. public static void main(String[] args) {
  5. Scanner in = new Scanner(System.in);
  6. int t = in.nextInt();
  7. int sum=0,j=3,k=5;
  8. for(int a0 = 0; a0 < t; a0++)
  9. {
  10. int n = in.nextInt();
  11. while(j<n)
  12. {
  13. sum=sum+j;
  14. j+=3;
  15. }
  16. while(k<n)
  17. {
  18. sum=sum+k;
  19. k+=5;
  20. }
  21. System.out.println(sum);
  22. sum=0;
  23. }
  24. }
  25. }

这段代码给我输出错误的结果。请解决这个问题。

英文:

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:

  1. import java.io.*;
  2. import java.util.*;
  3. public class Solution {
  4. public static void main(String[] args) {
  5. Scanner in = new Scanner(System.in);
  6. int t = in.nextInt();
  7. int sum=0,j=3,k=5;
  8. for(int a0 = 0; a0 &lt; t; a0++)
  9. {
  10. int n = in.nextInt();
  11. while(j&lt;n)
  12. {
  13. sum=sum+j;
  14. j+=3;
  15. }
  16. while(k&lt;n)
  17. {
  18. sum=sum+k;
  19. k+=5;
  20. }
  21. System.out.println(sum);
  22. sum=0;
  23. }
  24. }
  25. }

This code is giving me a wrong output. Please attend to this problem.

答案1

得分: 1

为了判断一个数字是否是另一个数字的倍数,最简单的方法是将一个数字除以另一个数字并检查余数。您从未这样做过。

我建议这样做:

  1. import java.util.Scanner;
  2. public class Main {
  3. private static final int THREE = 3;
  4. private static final int FIVE = 5;
  5. public static void main(String[] args) {
  6. Scanner in = new Scanner(System.in);
  7. int t = in.nextInt();
  8. int sum=0;
  9. for(int a0 = 0; a0 <= t; a0++)
  10. {
  11. if (a0 % THREE == 0 || a0 % FIVE == 0) {
  12. sum += a0;
  13. }
  14. }
  15. System.out.println(sum);
  16. }
  17. }
英文:

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 :

  1. import java.util.Scanner;
  2. public class Main {
  3. private static final int THREE = 3;
  4. private static final int FIVE = 5;
  5. public static void main(String[] args) {
  6. Scanner in = new Scanner(System.in);
  7. int t = in.nextInt();
  8. int sum=0;
  9. for(int a0 = 0; a0 &lt;= t; a0++)
  10. {
  11. if (a0 % THREE == 0 || a0 % FIVE == 0) {
  12. sum += a0;
  13. }
  14. }
  15. System.out.println(sum);
  16. }
  17. }

huangapple
  • 本文由 发表于 2020年8月28日 16:54:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63630566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定