In: Computer Science
Answer as soon as possible
Given a number, find the sum of all the unique multiples of
particular
numbers up to but not including that number.
If we list all the natural numbers below 20 that are multiples of 3
or 5, we
get 3, 5, 6, 9, 10, 12, 15, and 18.
The sum of these multiples is 78.
Given Code:
public int getSumOfMultiples(int i, int[] set) {
// Solution
return 0;
}
import java.util.*;
class Main
{
public int getSumOfMultiples(int i, int[] set) {
int sum = 0;
for(int i1 = 1; i1 < i; i1++)
{
for(int j = 0; j < set.length; j++)
{
if(i1 % set[j] == 0)
{
sum = sum + i1; // sum of all multiples
break;
}
}
}
return sum; // returns the sum
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the number : ");
int n = s.nextInt(); // read the number
System.out.print("Enter the size of the set : ");
int size = s.nextInt(); // read the set size
int set[] = new int[size];
System.out.print("Enter the elements in the set : ");
for(int i = 0; i < size; i++)
{
set[i] = s.nextInt(); // read the size
}
Main m = new Main();
int sum = m.getSumOfMultiples(n, set);
System.out.println("Sum of multiples : " + sum); // print the
result
}
}
OUTPUT :
