IN JAVA!!!!! Write a program called SumOfMultiples.java that, given a number n ,
ID: 3728081 • Letter: I
Question
IN JAVA!!!!!
Write a program called SumOfMultiples.java that, given a number n, prints the sum of: all multiples of 3 that are less than or equal to n. Thus, if n has the value 15, the multiples of 3 of interest are: 3, 6, 9, 12, 15, The sum of these is: 3+6+9+12+15 or 45. Thus, if your program looked like this (only the code inside main is shown):
The result seen on the screen should be 45. Hint: look at Module 6 and how we printed odd numbers. Then, modify that code to sum up odd numbers. Now, can you change this to sum up multiples of 3?
Write a program called ProductSumDifference.java that takes two integers a and b, with a < b, and computes the the value (a(a+1)(a+2) ... (b-1)b) - (a + (a+1) + .... + (b-1) + b).
In other words, what is the product of all numbers between a and b (including a and b )? And what is the sum of these numbers? The desired output is the product minus the sum. For example, if a=3 and b=7, the product-sum difference becomes (3 * 4 * 5 * 6 * 7) - (3 + 4 + 5 + 6 + 7) = 2520 - 25 = 2495.
Thus, your program should print out 2495.
Your program should define variables a and b so that their values can be changed when we test your programs. Thus, your code inside main will start like this:
You ought to test your program by trying out different values o f a and b
Explanation / Answer
SumOfMultiples.java
public class SumOfMultiples {
public static void main(String[] args) {
int n = 15;
int sum = 0;
for(int i=1;i<=n;i++) {
if(i%3 == 0) {
sum+=i;
}
}
System.out.println(sum);;
}
}
Output:
45
ProductSumDifference.java
public class ProductSumDifference {
public static void main(String[] args) {
int a = 3;
int b = 7;
int sum = 0;
int product = 1;
for(int i=a;i<=b;i++) {
sum+=i;
product*=i;
}
System.out.println(product-sum);
}
}
Output:
2495