java - The sum of all the multiples of 3 or 5 below N -
i have find sum of multiples of 3 or 5 below n. example if have list natural numbers below 10 multiples of 3 or 5, 3, 5, 6 , 9,the sum of these multiples 23.
now problem left want able read numbers display sum, reads 1 number , display sum right after it, ideas?
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; (int = 0; < nn; i++) { if (((i % 3) == 0) || ((i % 5) == 0)) { s = s + i; } } return (s); } }
i suggest use scanner
. suggest add sum
iterating 3
n
in increments of 3
. 5
n
in increments of 5
(then exclude multiples of 3
, because they've been added). like
public static void main(string[] args) { scanner scanner = new scanner(system.in); while (scanner.hasnextint()) { int n = scanner.nextint(); system.out.println(getsum(n)); } } public static long getsum(int n) { long sum = 0; (int = 3; < n; += 3) { sum += i; } (int = 5; < n; += 5) { if (i % 3 != 0) { // <-- added if divisible 3 sum += i; } } return sum; }
based on comment below, change main
first read int
of counts, store them in array. like
public static void main(string[] args) { scanner scanner = new scanner(system.in); while (scanner.hasnextint()) { int toread = scanner.nextint(); int[] vals = new int[toread]; (int t = 0; t < toread; t++) { if (scanner.hasnextint()) { vals[t] = scanner.nextint(); } } stringbuilder sb = new stringbuilder(); (int n : vals) { sb.append(getsum(n)).append(" "); } system.out.println(sb); } }
Comments
Post a Comment