Created
February 24, 2015 18:19
-
-
Save heckenmann/ea611541217535f5cb9d to your computer and use it in GitHub Desktop.
Gaußsche Summenformel / “Kleiner Gauß”
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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