Seuraava pseudokoodi esittää funktion count
, joka laskee summan 1+2+\dots+n.
function count(n) total = 0 for i = 1 to n total += i return total
Toteuta pseudokoodia vastaava funktio Pythonilla tai Javalla.
Python
Toteuta tiedostoon sum.py
funktio count
, joka laskee summan.
def count(n): # TODO if __name__ == "__main__": print(count(1)) # 1 print(count(2)) # 3 print(count(3)) # 6 print(count(10)) # 55 print(count(123)) # 7626
Java
Toteuta tiedostoon Sum.java
metodi count
, joka laskee summan.
public class Sum { public int count(int n) { // TODO } public static void main(String[] args) { Sum s = new Sum(); System.out.println(s.count(1)); // 1 System.out.println(s.count(2)); // 3 System.out.println(s.count(3)); // 6 System.out.println(s.count(10)); // 55 System.out.println(s.count(123)); // 7626 } }