Skip to content

Instantly share code, notes, and snippets.

@heckenmann
Created February 24, 2015 18:19
Show Gist options
  • Save heckenmann/ea611541217535f5cb9d to your computer and use it in GitHub Desktop.
Save heckenmann/ea611541217535f5cb9d to your computer and use it in GitHub Desktop.
Gaußsche Summenformel / “Kleiner Gauß”
public class KleinerGauss
{
public static void main(String[] args) {
System.out.println(berechneSchleife(10));
System.out.println(berechneKG(10));
}
// Berechnet den Wert mittels for-Schleife
public static int berechneSchleife(int n) {
int ergebnis = 0; // Das Ergebnis, das zurückgegeben wird
for(int k = 1; k <= n; k++) {
ergebnis += k;
}
return ergebnis;
}
// Berechnet den Wert mittels Gaußscher Summenformel
public static int berechneKG(int n) {
// Eingaben < 0 werden abgefangen
if(n < 0) {
return 0;
}
int ergebnis = (n*(n+1))/2; // Das Ergebnis, das zurückgegeben wird
return ergebnis;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment