Commit 9958d4b3 by Patryk Czarnik

Przykłady dot operacji na liczbach

parent 4d33c128
package pcz.p04_operatory;
public class Bitowe1 {
public static void main(String[] args) {
byte x = 25;
byte y = -25;
byte shift = 2;
System.out.printf("x = %d y = %d %n", x, y);
System.out.println("Bez przycinania (w zakresie int):");
System.out.printf("x << %d = %d %n", shift, x << shift);
System.out.printf("y << %d = %d %n", shift, y << shift);
System.out.printf("x >> %d = %d %n", shift, x >> shift);
System.out.printf("y >> %d = %d %n", shift, y >> shift);
System.out.printf("x >>> %d = %d %n", shift, x >>> shift);
System.out.printf("y >>> %d = %d %n", shift, y >>> shift);
System.out.println();
System.out.println("Przycięte do byte: ");
System.out.printf("x << %d = %d %n", shift, (byte)(x << shift));
System.out.printf("y << %d = %d %n", shift, (byte)(y << shift));
System.out.printf("x >> %d = %d %n", shift, (byte)(x >> shift));
System.out.printf("y >> %d = %d %n", shift, (byte)(y >> shift));
System.out.printf("x >>> %d = %d %n", shift, (byte)(x >>> shift));
System.out.printf("y >>> %d = %d %n", shift, (byte)(y >>> shift));
}
}
package pcz.p04_operatory;
public class Bitowe2 {
public static void main(String[] args) {
int x = 0b00000000000000000000000000011001;
int y = -x;
int z = 0b11111111111111111111111111100111;
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println();
System.out.println("<<");
System.out.println(x << 2);
System.out.println(y << 2);
System.out.println(z << 2);
System.out.println(0b11111111111111111111111110011100); // -100
System.out.println();
System.out.println(">>");
System.out.println(x >> 2);
System.out.println(y >> 2);
System.out.println(0b11111111111111111111111111111001);
System.out.println();
System.out.println(">>>");
System.out.println(x >>> 2);
System.out.println(y >>> 2);
System.out.println(0b00111111111111111111111111111001);
System.out.println();
}
}
package pcz.p04_operatory;
public class Leniwosc1 {
public static void gorliwa() {
// opertor "gorliwy"
// zawsze oblicza obie strony wyrażenia logicznego, a dopiero potem daje wynik false / true
if(lewy() & prawy()) {
System.out.println("prawda");
} else {
System.out.println("fałsz");
}
}
public static void leniwa() {
// operator "leniwy"
// jeśli lewa strona rozstrzyga o ostatecznym wyniku, to prawa strona nie jest sprawdzana
if(lewy() && prawy()) {
System.out.println("prawda");
} else {
System.out.println("fałsz");
}
}
private static boolean lewy() {
System.out.print("lewy ");
return false;
}
private static boolean prawy() {
System.out.print("prawy ");
return true;
}
public static void main(String[] args) {
System.out.println("wersja gorliwa");
gorliwa();
System.out.println("\nwersja leniwa:");
leniwa();
}
}
package pcz.p04_operatory;
public class Leniwosc2 {
public static void main(String[] args) {
int x = 0, y = 0;
if(++x > 0 | y++ > 0) {
System.out.println("prawda");
} else {
System.out.println("fałsz");
}
System.out.println("x == " + x);
System.out.println("y == " + y);
System.out.println();
x = y = 0;
if(++x > 0 || y++ > 0) {
System.out.println("prawda");
} else {
System.out.println("fałsz");
}
System.out.println("x == " + x);
System.out.println("y == " + y);
System.out.println();
x = y = 0;
if(x++ > 0 || ++y > 0) {
System.out.println("prawda");
} else {
System.out.println("fałsz");
}
System.out.println("x == " + x);
System.out.println("y == " + y);
}
}
package pcz.p04_operatory;
public class Leniwosc3 {
public static void main(String[] args) {
int x = 0, y = 0;
if(x++ > 0 || y++ > 0) {
System.out.println("prawda");
} else {
System.out.println("fałsz");
}
System.out.println("x == " + x);
System.out.println("y == " + y);
System.out.println();
x = y = 0;
if(++x > 0 || ++y > 0) {
System.out.println("prawda");
} else {
System.out.println("fałsz");
}
System.out.println("x == " + x);
System.out.println("y == " + y);
}
}
package pcz.p04_operatory;
public class Leniwosc4 {
public static void main(String[] args) {
// z prawdopodobieństwem 0.33 na imie wpisz nulla
// z prawdopodobieństwem 0.33 na imie wpisz "Ala"
// z prawdopodobieństwem 0.34 na imie wpisz "Tadeusz"
double los = Math.random();
String imie;
if(los < 0.33) {
imie = null;
} else if(los < 0.66) {
imie = "Ala";
} else {
imie = "Tadeusz";
}
System.out.println("imie = " + imie);
// if(imie != null & imie.length() >= 5) {
// System.out.println("długie imię");
// } else {
// System.out.println("null albo krótkie imię");
// }
// jeśli imie będzie null, to w ogóle nie przejdziemy do drugiej części sprawdzenia
if(imie != null && imie.length() >= 5) {
System.out.println("długie imię");
} else {
System.out.println("null albo krótkie imię");
}
if(imie == null || imie.isEmpty()) {
System.out.println("Brak danych");
}
if(args.length >= 1 && "Ala".equalsIgnoreCase(args[0])) {
System.out.println("Ala ma kota");
}
}
}
package pcz.p04_operatory;
import java.util.Random;
public class Logiczne {
public static void main(String[] args) {
Random random = new Random();
int x = random.nextInt(1000);
int y = random.nextInt(1000);
System.out.println("Wylosowane liczby: " + x + " , " + y);
// koniunkcja, logiczne "i"
// alternatywa, logiczne "lub"
if(x > 500 && y > 500) {
System.out.println("Obie liczby > 500");
} else {
System.out.println("Któraś z liczb <= 500");
}
if(x > 500 || y > 500) {
System.out.println("Co najmniej jedna z liczb > 500");
} else {
System.out.println("Obie liczby <= 500");
}
// alternatywa rozłączna, "albo", technicznie "xor" (exclusive or)
if((x > 500) ^ (y > 500)) {
System.out.println("Dokładnie jedna z liczb > 500");
} else {
System.out.println("Obie liczby są > 500 albo obie liczby są <= 500");
}
// ! negacja
if(!(x % 3 == 0)) {
System.out.println("Nieprawda, że liczba jest podzielna przez 3");
}
}
}
package pcz.p04_operatory;
public class OperatorWarunkowy1 {
public static void main(String[] args) {
int x = 10;
String s;
s = x > 10 ? "A" : "B";
System.out.println(s);
// różwnoważne:
if(x > 10) {
s = "A";
} else {
s = "B";
}
s = x > 10 ? "A" : x > 5 ? "B" : "C";
System.out.println(s);
s = x > 10 ? "A" : (x > 5 ? "B" : "C");
System.out.println(s);
s = x > 8 ? x < 20 ? "A" : "B" : " C";
System.out.println(s);
s = x > 8 ? (x < 20 ? "A" : "B") : " C";
System.out.println(s);
s = x > 8 ? x < 20 ? "A" : "B" : x % 2 == 0 ? "C" : " D";
System.out.println(s);
s = x > 8 ? (x < 20 ? "A" : "B") : (x % 2 == 0 ? "C" : " D");
}
}
package pcz.p04_operatory;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class OperatorWarunkowy2 {
public static void main(String[] args) {
int[] liczby = { 100, 10, 20, 150, 7, 120 };
String wynik = IntStream.of(liczby)
.mapToObj(a -> a >= 100 ? "duże" : "małe")
.collect(Collectors.joining("; "));
System.out.println(wynik);
}
}
package pcz.p04_operatory;
public class OperatorWarunkowy3 {
public static void main(String[] args) {
// ilustracja zastosowań:
String s = Math.random() > 0.5 ? "ala" : null;
if(s != null && s.length() > 2) {
System.out.println("ok");
} else {
System.out.println("puste");
}
}
}
package pcz.p04_operatory;
public class PlusPlus {
public static void main(String[] args) {
int x;
int y;
x = 10;
y = ++x;
System.out.println("++x preinkrementacja");
System.out.println("x: " + x + " , y: " + y);
System.out.println();
x = 20;
y = x++;
System.out.println("x++ postinkrementacja");
System.out.println("x: " + x + " , y: " + y);
System.out.println();
x = 50;
System.out.println(x++);
System.out.println(++x);
System.out.println();
Integer a = 100;
a++;
System.out.println(a); // a wskazuje już na inny obiekt
System.out.println();
double d = 0.5;
System.out.println(d);
d++; // można inkrementować też float i double
System.out.println(d);
System.out.println();
y = x = 100;
System.out.println("x: " + x + " , y: " + y);
y = 33;
y = x += 5; // x zwiększam o 5, a to co wyjdzie, wpisuję także na y
System.out.println(" += 5");
System.out.println("x: " + x + " , y: " + y);
}
}
package pcz.p04_operatory;
public class PlusPlusZagadki {
public static void main(String[] args) {
int x, y, z;
x = 1;
x = x++ + ++x; // 1 + 3
System.out.println(x);
x = 1;
x = ++x + x++; // 2 + 2
System.out.println(x);
y = 1;
y += y++;
// y = (y + y++)
// y = 1 + 1
System.out.println(y);
z = 1;
z += z++ + ++z;
// z = z + z++ + ++z
// z = 1 + 1 + 3 = 5
System.out.println(z);
}
}
package pcz.p04_operatory;
public class PlusPlusZastosowania {
static int suma(int[] t) {
int suma = 0;
int i = 0;
while(i < t.length) {
suma += t[i++];
}
return suma;
}
public static void main(String[] args) {
int[] a = { 10, 20, 30, 40 };
System.out.println(suma(a));
}
}
package pcz.p04_operatory;
public class Przypisania {
public static void main(String[] args) {
int x, y, z;
z = y = x = 10;
System.out.printf("x=%d, y=%d, z=%d%n", x, y, z);
x = 10;
y = 50;
z = 100;
z += y = x += 3;
System.out.printf("x=%d, y=%d, z=%d%n", x, y, z);
}
}
package pcz.p04_operatory;
import javax.swing.JOptionPane;
public class ZastosowaniaLeniwychOperatorow {
public static void main(String[] args) {
String imie = JOptionPane.showInputDialog("Jak masz na imię?");
if(imie != null && imie.length() <= 3) {
JOptionPane.showMessageDialog(null, "Masz krótkie imię");
}
// Gdybym nie sprawdzał czy napis nie jest nullem,
// to w przypadku Cancel dochodziłoby do błedu NullPointerException (NPE)
// w momencie próby wywołania length()
// if (imie.length() <= 3) {
// JOptionPane.showMessageDialog(null, "Masz krótkie imię");
// }
// Gdybym zamiast "leniwego" && użył "gorliwego" &
// to także doszłoby do błędu, bo Java sprawdzałaby prawą stronę warunku nawet wtedy gdy lewa jest fałszem
// if(imie != null & imie.length() <= 3) {
// JOptionPane.showMessageDialog(null, "Masz krótkie imię");
// }
String jezyk = JOptionPane.showInputDialog("Jaki jest Twój ulubiony język programowania?");
if(jezyk != null && jezyk.equals("Java")) {
JOptionPane.showMessageDialog(null, "Brawo");
} else {
JOptionPane.showMessageDialog(null, "Źle");
}
// jeśli chodzi o tę konkretną sytuację, to pisząc w tej kolejności zapobiegamy wyjątkowi NPE
if("Java".equals(jezyk)) {
JOptionPane.showMessageDialog(null, "Brawo");
} else {
JOptionPane.showMessageDialog(null, "Źle");
}
}
}
package pcz.p05_liczby;
public class BityIBajty {
public static void main(String[] args) {
System.out.println("Zwiększanie bajta:");
byte b = 0;
for(int i = 1; i <= 260; i++) {
String bity = Integer.toBinaryString(Byte.toUnsignedInt(b));
bity = String.format("%8s", bity);
bity = bity.replace(' ', '0');
System.out.printf("%4d : %s%n", b, bity);
b++;
}
}
}
package pcz.p05_liczby;
public class Ciekawostki {
public static void main(String[] args) {
int x = 5, y = 1000000000;
int z = x * y;
System.out.println(z);
System.out.println(5 * 1000000000);
System.out.println(5L * 1000000000);
System.out.println(3 * 1000000000);
// Gdy wynik obliczenia nie mieści się w zakresie dla danego typu (int lub long)
// dochodzi do "integer overflow". W Javie nie powoduje to błędu (w sensie wyjątku),
// po prostu wychodzi "przekręcony" wynik.
System.out.println();
double a = 3.0, b = 1.2;
System.out.println(a * b);
System.out.println(3 * 1.2);
double oczekiwany = 3.6;
if(a * b == oczekiwany) {
System.out.println("OK");
} else {
System.out.println("Nie OK");
System.out.println(3.6 - 3 * 1.2);
}
System.out.println();
// Liczby zmiennoprzecinkowe (w Javie: float i double) działają w przybliżeniu.
// W pamięci są zapisany w systemie dwójkowym, a nie dziesiętnym, więc zaokrąglenia nastepują w zapisie binarnym liczby, co utrudnia zrozumienie.
// Praktyczny morał: double nie używa się do liczenia pieniędzy.
// Lepszą alternatywą jest wyspecjalizowana klasa BigDecimal.
// Liczba całkowita zapisana w kodzie zaczynając od cyfry 0, jest w systemie ósemkowym.
int n = 0321; // = 3*64 + 2*8 + 1*1
System.out.println(n);
System.out.println(0321);
//NK int m = 098;
System.out.println();
// Od Javy 7 między cyframi można wpisywać znaki _ , które nie zmieniają wartości
int i = 123_456_789;
System.out.println(i);
int j = 123____4___5;
System.out.println(j);
}
}
package pcz.p05_liczby;
public class Dzielenie {
public static void main(String[] args) {
double d = 1.25;
int n = 5;
// Uwaga na kolejność działań gdy miesza się inty i double
// Tutaj: int dzielony porzez int - wynik obcinany do liczby całkowitej
System.out.println(n / 3 * d);
// dzielenie na doublach
System.out.println(n * d / 3);
System.out.println(1.0 * n / 3 * d);
System.out.println((double)n / 3 * d);
System.out.println();
System.out.println("Dzielenie całkowite i reszta z dzielenia:");
for(int i = -10; i <= 10; i++) {
System.out.printf("%3d / 3 = %2d %3d %% 3 = %2d\n", i, i / 3, i, i % 3);
}
}
}
package pcz.p05_liczby;
public class Floaty {
public static void main(String[] args) {
float f = 1.0000001f;
System.out.println(f);
f += 1;
System.out.println(f);
f -= 1;
System.out.println(f);
System.out.println();
// Zaokroglęnia nie są robione w systemie dziesiętnym, tylko dwójkowym
f = 1.0000003f;
System.out.println(f);
f += 1;
System.out.println(f);
f -= 1;
System.out.println(f);
System.out.println();
f = 2222222222f;
// System.out.println(f);
System.out.printf("%8.0f\n", f);
f += 1000;
System.out.printf("%8.0f\n", f);
f -= 10000000;
System.out.printf("%8.0f\n", f);
// lepsze dla pieniędzy: BigDecimal
}
}
package pcz.p05_liczby;
public class IntegerOverflow {
public static void main(String[] args) {
System.out.println(2 * 1000_000_000);
System.out.println(3 * 1000_000_000);
System.out.println(5 * 1000_000_000);
System.out.println(3L * 1000_000_000);
System.out.println();
int x = 2147483646;
System.out.println(x);
x++;
System.out.println(x);
x++;
System.out.println(x);
x++;
System.out.println(x);
}
}
package pcz.p05_liczby;
import java.util.Scanner;
public class JakSprawdzicOverflow {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Podaj pierwszą liczbę: ");
int x = sc.nextInt();
System.out.println("Podaj drugą liczbę: ");
int y = sc.nextInt();
int iloczyn = x * y;
System.out.println("Wynik zwykłego mnożenia: " + iloczyn);
try {
int sprawdzony = Math.multiplyExact(x, y);
System.out.println("Wynik zabezpieczonego mnożenia: " + sprawdzony);
} catch(ArithmeticException e) {
System.out.println("Overflow");
}
}
}
// YT "Ariane 5"
// przerwa do 13:30
package pcz.p05_liczby;
public class LiteralyLiczbowe {
public static void main(String[] args) {
int x;
x = 123; // format dziesiętny
System.out.println(x);
x = 0123; // system ósemkowy
//NK x = 08; // cyfry od 0 do 7
System.out.println(x);
x = 0x100; // system szesnastkowy
System.out.println(x);
x = 0x7F;
System.out.println(x);
// system dwójkowy - od Javy 7
x = 0b1101;
System.out.println(x);
// odstępy pomiędzy cyframi - od Javy 7
x = 2_000_000;
System.out.println(x);
//NK long l = 4000000000; // wartość nie mieszcząca się w int
long l = 4000000000L; // OK
// int _1000 = 1313;
// x = _1000; // odwołanie do zmiennej :)
// x = 1000_;
x = 10______00; // po prostu tysiąc
// dopuszczalne są tylko pomiędzy cyframi.
// nie na początku, nie na końcu, nie obok kropki ani obok litery typu i wykładnika
x = 0x0F_FF_80_00;
x = 0b0011_0101;
System.out.println(x); // 1000
double dd = 10__00;
dd = 3.14; // literał liczbowy z częścią ułamkową jest typu double (a nie float)
dd = 1_00.0__0;
//dd = 100._9;
//dd = 100_.9;
dd = 100.99d;
//dd = 100.99_f;
// x = 0x_FF;
// NK x = 1L; // L na końcu oznacza typ long (może być duże lub małe)
l = 1L;
l = 1; // inta można wpisać na zmienną long
System.out.println();
float f = 12; // int na float - OK
// f = 3.14;
// literał z ułamkiem jest typu double, a double nie można wpisać na float
f = 3.14F;
f = 1.0f;
f = 3f;
f = 1.13e2F;
f = (float)3.14; // kompiluje się, ale niezalecane, bo można zgubić precyzję
System.out.println(f);
double d = 3.14;
// NK f = d;
// na końcu double'a też można podać info o typie: D albo d
d = 4.44d;
d = 4.445D;
// liczba w notacji dziesiętnej razy 10 do podanej potęgi
d = 1.25e3;
System.out.println(d);
d = 4.44e-3;
System.out.println(d);
System.out.println();
// liczba w notacji szestastkowej razy 2 do podanej potęgi - tak to jest przechowywane wewnętrznie!
d = 0x3p2; // 12
System.out.println(d);
d = 0x0.2p0; // 2/16 = 1/8 = 0.125
System.out.println(d);
d = 0x1p-3;
System.out.println(d);
}
}
package pcz.p05_liczby;
public class PomylonyDouble {
public static void zaszachraj(int n, double arg) {
System.out.println("mnożenie : " + n * arg);
double suma = 0.0;
for(int i = 1; i <= n; i++) {
suma += arg;
}
System.out.println("dodawanie: " + suma);
System.out.println();
}
public static void main(String[] args) {
zaszachraj(1000, 0.5); // 1/2
zaszachraj(1000, 0.125); // 1/8
zaszachraj(1000, 0.2); // 1/5 - nieskończone rozwinięcie w systemie dwójkowym
zaszachraj(1000, 0.3);
zaszachraj(1000, 1.0 / 3.0);
}
}
package pcz.p05_liczby;
public class ProcentyNaCalkowitych {
public static void main(String[] args) {
long netto = 10005;
long procent = 23;
long brutto = (netto * (100 + procent) + 50) / 100;
System.out.println(brutto);
}
}
package pcz.p05_liczby;
public class PrzeciazanieIntLong {
public static void main(String[] args) {
try {
System.out.println("oblicza w wersji int:");
System.out.println(Math.multiplyExact(5, 1000_000_000));
} catch(Exception e) {
System.out.println("wersja int: wyjątek " + e);
}
System.out.println();
try {
System.out.println("oblicza w wersji long:");
System.out.println(Math.multiplyExact(5L, 1000_000_000L));
} catch(Exception e) {
System.out.println("wersja long: wyjątek " + e);
}
}
}
package pcz.p05_liczby;
public class Rzutowania {
// "Hierarchia" typów prostych:
// byte < short < int < long < float < double
// char < int
public static void main(String[] args) {
int x = 107;
float f = 3.14f;
long l3 = 13;
// rzutowanie niejawne - na zmienną typu "szerszego" można zapisać wartość typu "węższego" (widening)
long l = x;
float f2 = l3;
//NK x = l;
//NK l = f;
f = l;
// rzutowanie jawne można stosować zawsze; czasem może wiązać się z "popsuciem" wartości liczbowej
x = (int)l;
System.out.println(x);
// można stosować jawne rzutowanie nawet gdy nie jest konieczne
l = x;
l = (long)x;
System.out.println(l);
l = 4_000_000_000L;
x = (int)l;
System.out.println(x); // zmieniona wartość, ostatnie 32 bity z zapisu tej liczby
f = 100.99F;
x = (int)f; // obcina do wartości całkowitej
System.out.println(x); // 100
f = 4e9f; // 4 * 10^9 czyli 4mld
x = (int)f; // po wyjściu poza zakres przyjmuje MAXINT / MININT
System.out.println(x);
// Na zmienne typu byte, short i char można wpisywać konkretne wartości całkowite, o ile kompilator widzi, że mieszczą się w zakresie
byte b1 = 100;
//NK byte b2 = 200;
x = 100;
//NK byte b3 = x;
final int fi = 10;
b1 = fi; // jeśli wartość jest "stałą" (jest final i jest znana w czasie kompilacji)
b1 = 50;
//NK b1 = x; // bo "nie każdy int mieści się w byte"
x = b1; // OK, bo byte mieści się w int
//NK int i3 = 3L;
float f3 = 3L;
byte b = 13;
b = 15;
//NK b = 130;
x = 15;
//NK b = x;
b = (byte)x;
//NK wezByte(88);
wezByte((byte)88);
wezByte(b);
System.out.println();
System.out.println(dajByte());
System.out.println(dajZnak());
System.out.println();
l = 5_000_000_000L;
x = (int)l;
System.out.println(x);
// rzutowanie liczb całkowitych - bierzemye ostatnie bity z zapisu liczby w pamięci
// zobaczę to samo, co w int overflow gdy mnożyłem 5 * 1000000000
System.out.println("5mld long rzut na int: " + x);
double d = 5_000_000_000.0;
x = (int)d;
System.out.println("5mld double rzut na int: " + x);
// rzutowanie float i double na liczbę całkowitą - bierzemy wartość, która jest najbliżej,
// w tym przypadku będzie to Integer.MAX_VALUE
byte b2 = 40, b3 = 50;
// Operacje arytmetyczne + - * / % - są zdefiniowane dla typu int, a nie dla byte i short
// dlatego ich ywniki trzeba zrzutowa, aby pisać na zmienne tych typów
//NK byte b4 = b2 + b3;
byte b4 = (byte)(b2 + b3);
// ale bez rzutowania działają ++ i +=
System.out.println(b2);
b2++;
System.out.println(b2);
b2 += 10;
System.out.println(b2);
}
static byte dajByte() {
return 65;
}
/* NK
static byte dajByteInaczej() {
int x = 65;
return x;
}
*/
static char dajZnak() {
return 65;
}
static void wezByte(byte bbb) {
System.out.println(bbb);
}
}
package pcz.p05_liczby;
import java.util.Scanner;
public class Silnia {
// 1 * 2 * 3 * .... * n
static long silnia(int n) {
long wynik = 1;
for(int i = 2; i <= n; i++) {
wynik *= i;
}
return wynik;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("Podaj liczbę (-1 aby zakończyć)");
int n = sc.nextInt();
if(n < 0)
break;
long wynik = silnia(n);
System.out.println("Wynik: " + wynik);
}
}
}
package pcz.p05_liczby;
import java.math.BigInteger;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class SilniaNaRozneSposoby {
static int silniaInt(int n) {
int wynik = 1;
for(int i = 2; i <= n; i++) {
wynik *= i;
}
return wynik;
}
static long silniaFor(int n) {
long wynik = 1;
for(int i = 2; i <= n; i++) {
wynik *= i;
}
return wynik;
}
static long silniaWhile(int n) {
long wynik = 1;
while(n > 1) {
wynik *= n;
n--;
}
return wynik;
}
static long silniaRek(int n) {
// rekurencja
if(n < 2) {
return 1;
} else {
return n * silniaRek(n - 1);
}
}
static BigInteger silniaBig(int n) {
BigInteger wynik = BigInteger.ONE;
for(int i = 2; i <= n; i++) {
wynik = wynik.multiply(BigInteger.valueOf(i));
}
return wynik;
}
static long silniaKontrolowana(int n) {
long wynik = 1;
for(int i = 2; i <= n; i++) {
wynik = Math.multiplyExact(wynik, i);
}
return wynik;
}
static long silniaFun(int n) {
// też OK return LongStream.rangeClosed(1, n).reduce(1, Math::multiplyExact );
return LongStream.rangeClosed(1L, n).reduce(1L, (wynik, i) -> wynik * i);
}
static BigInteger silniaBigFun(int n) {
return IntStream.rangeClosed(1, n)
.mapToObj(BigInteger::valueOf)
.reduce(BigInteger.ONE, BigInteger::multiply);
}
public static void main(String[] args) {
int wynik1 = silniaInt(5);
System.out.println(wynik1);
System.out.println("int, for:");
for(int arg = 0; arg <= 50; arg++) {
System.out.println(arg + "! = " + silniaInt(arg));
}
System.out.println();
System.out.println("long, for:");
for(int arg = 0; arg <= 50; arg++) {
System.out.println(arg + "! = " + silniaFor(arg));
}
System.out.println();
System.out.println("long, while:");
for(int arg = 0; arg <= 50; arg++) {
System.out.println(arg + "! = " + silniaWhile(arg));
}
System.out.println();
System.out.println("long, rekurencja:");
for(int arg = 0; arg <= 50; arg++) {
System.out.println(arg + "! = " + silniaRek(arg));
}
System.out.println();
System.out.println("long, multiplyExact:");
for(int arg = 0; arg <= 50; arg++) {
try {
System.out.println(arg + "! = " + silniaKontrolowana(arg));
} catch(ArithmeticException e) {
System.out.println("OVERFLOW");
}
}
System.out.println();
System.out.println("BigInteger, for:");
for(int arg = 0; arg <= 100; arg++) {
System.out.println(arg + "! = " + silniaBig(arg));
}
System.out.println();
System.out.println("long, reduce:");
for(int arg = 0; arg <= 50; arg++) {
System.out.println(arg + "! = " + silniaFun(arg));
}
System.out.println();
System.out.println("BigInteger, reduce:");
for(int arg = 0; arg <= 100; arg++) {
System.out.println(arg + "! = " + silniaBigFun(arg));
}
System.out.println();
}
}
/* wersja w Pythonie:
def silnia(n):
wynik = 1
for i in range(1, n+1):
wynik *= i
return wynik
print(silnia(1))
print(silnia(5))
print(silnia(100))
*/
/* wersja w Haskellu:
silnia n = foldl (*) 1 [1..n]
silnia 5
silnia 100
*/
package pcz.p05_liczby;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
public class TestMegaSilni {
public static void main(String[] args) {
System.out.println("Wyliczam silnię od 100 tys.");
BigInteger silnia100tys = SilniaNaRozneSposoby.silniaBig(100_000);
String silnia100tysTXT = silnia100tys.toString();
System.out.printf("Gotowe, wynik ma %d cyfr.", silnia100tysTXT.length());
try {
final String plik = "silnia_100_tys.txt";
Files.write(Paths.get(plik), Collections.singleton(silnia100tysTXT), Charset.defaultCharset(),
StandardOpenOption.CREATE);
System.out.println("Zapisałem do pliku " + plik);
} catch(IOException e) {
System.out.println("Błąd zapisu do pliku");
}
System.out.println();
}
}
package pcz.p05_liczby;
public class WypiszZakresy {
public static void main(String[] args) {
System.out.println("byte " + Byte.BYTES + " bajtów, od " + Byte.MIN_VALUE + " do " + Byte.MAX_VALUE);
System.out.println("short " + Short.BYTES + " bajtów, od " + Short.MIN_VALUE + " do " + Short.MAX_VALUE);
System.out.println("int " + Integer.BYTES + " bajtów, od " + Integer.MIN_VALUE + " do " + Integer.MAX_VALUE);
System.out.println("long " + Long.BYTES + " bajtów, od " + Long.MIN_VALUE + " do " + Long.MAX_VALUE);
System.out.println("char " + Character.BYTES + " bajtów, od " + (int)Character.MIN_VALUE + " do "
+ (int)Character.MAX_VALUE);
System.out.println();
// bez ograniczen: klasy BigInteger (calkowite) i BigDecimal (z ulamkiem)
System.out.println("float " + Float.BYTES + " bajtów, od " + Float.MIN_VALUE + " do " + Float.MAX_VALUE);
System.out.println(" min normal : " + Float.MIN_NORMAL);
System.out.println("double " + Double.BYTES + " bajtów, od " + Double.MIN_VALUE + " do " + Double.MAX_VALUE);
System.out.println(" min normal : " + Double.MIN_NORMAL);
System.out.println();
System.out.println("boolean : false i true");
}
}
package pcz.p05_liczby;
public class Znaki {
public static void main(String[] args) {
System.out.println("A");
System.out.println("A" + 5);
System.out.println('A');
System.out.println('A' + 5);
System.out.println('A' + 'B');
System.out.println();
char c = 65; // można wpisywać konkretną wartość int, o ile mieści się w zakresie
//NK char d = -1;
int x = 65;
int y = 'A';
//NK c = x; // ale nie int-a ze zmiennej
c = (char)x;
System.out.println(c);
x = c;
System.out.println(x);
x = (int)c;
System.out.println((int)c);
System.out.println();
for(char znak = 'A'; znak <= 'Z'; znak++) {
System.out.print(znak + " ");
}
System.out.println();
int ącki = 'Ą';
System.out.println(ącki);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment