Java – Project Euler Multiples
Posted Nov 21st, 2009 by ConorThis weeks ICSP assignment was one of the Project Euler challenges. Here is the task:
This weeks Bonus Task is to solve the First Problem using Java:
“If we list all the natural numbers below 10 that are multiples of 3
or 5, we * get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.”
In the code below, I have achieved this objective and also expanded on it. My program allows you to pass on two multiples and a max integer value to the program for which to calculate the results. You can execute:
java Multiples 3 5 1000
That command will find the sum of multiples of 3 and 5 below 1000, as stated in the task. You can also change the values to calculate different sums. The code for Multiples.java is below:
/*
* Developer: Conor Mac Aoidh
* Homepage: http://blog.macaoidh.name/2009/11/21/java-project-euler-multiples/
*/
public class Multiples{
public static void main(String[] args){
Multiples multiples=new Multiples();
int one=0;
int two=0;
int max=0;
if(args.length==3){
try{
one=Integer.parseInt(args[0]);
two=Integer.parseInt(args[1]);
max=Integer.parseInt(args[2]);
}
catch(NumberFormatException e){
System.err.println("Argument must be an integer");
System.exit(1);
}
}
else
System.out.println("You must supply integers in the format:\n multiple_one multiple_two max_integer");
int sum=multiples.sum(one,two,max);
System.out.println("Find the sum of all the multiples of "+one+" or "+two+" below "+max);
System.out.println("Sum:"+sum);
}
public int sum(int one,int two,int max){
int i=0;
int sum=0;
for(i=0;i<max ;i++){
if(i % one==0)
sum=sum+i;
if(i % two==0)
sum=sum+i;
}
return sum;
}
}
Simple as that!
i like these puzzles. always interesting.
only thing i’d change is to make it slightly more readable. eg, the (i%one==0) should be more like ((i%one)==0) or (!(i%one))
also, sum=sum+i can be simplified to sum+=i
please give me your java project it may be simple as possible
the project code is above..