+4

# sum of n numbers divisible by 5,why can write code in Java?.....I need the sum of all(n) the numbers, which are divisible by 5.

Mathematics

5 Answers

New Answer

+4

public class Demo { public static void main(String[] args) { int sum = 0; int num = 100; for (int i = 1; i <= num; i++) { if (i % 5 == 0) { System.out.println(i + " "); sum += i; } } System.out.println("Sum" + sum); } }

+19

2 ways : ● make an infinite loop starting from 1 [put a break; statement in it & will execute it when n multiples of 5 are found for that use a variable k=0 & increment it every time a multiple of 5 is find & when k==n then break; through loop & using Sum variable sum up those multiples.] ● Mathematical way to solve in 1 line : 5, 10, 15 ... 5n //n numbers Sn = (n)(5+5n)/2 //AP sum formula . //so just print direct result using Sn formula 👍 Satnam Singh 👑 code for testing divisibility with 5 & Mohammad hussain code [if n>20 then code will not work good, so outer limit must be infinity & need of break; statement , though your logic is correct ☺👍]

+13

https://code.sololearn.com/cj7v4lB64kix/?ref=app

+2

Thanks to all

+1

public static int sumOfNDBy5(int num) } int sum = 0; for (int i = 0; i <= num; i += 5) sum += i; return sum; }