terça-feira, 29 de novembro de 2011

Projeto Euler [Problema 1]

Solucionando o Problema 1 do Projeto Euler
Descrição do Problema: 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.


Código:
package br.com.projetoeuler.problema1;
/**
 * Problema1
 *  
 * @author Lucas Frizzo
 * lucas-frizzo.blogspot.com
 */
public class Problema1 {
 private int numero; 
 
 public int getNumero() {
  return numero;
 }
 
 public void setNumero(int numero) {
  this.numero = numero;
 }
 
 public int somaDosMultiplos(Problema1 problema1){
  int soma = 0;
  int numero = problema1.getNumero();
  
  for (int i = 1; i < numero; i++) {
   if (i % 3 == 0 || i % 5 == 0) {
    soma = soma + i;
   }
  }
  return soma;
 }

}

package br.com.projetoeuler.problema1;

public class TesteProblema1 {
 public static void main(String[] args) {
  Problema1 problema1 = new Problema1();
  problema1.setNumero(1000);
  
  System.out.println("Soma de todos os multiplos de 3 e 5 menores que " +
    ""+problema1.getNumero()+" = "+problema1.somaDosMultiplos(problema1));
 }
}


Resposta:
Soma de todos os multiplos de 3 e 5 menores que 1000 = 233168



Nenhum comentário:

Postar um comentário