Jakiś problem?

Najmniejsza Wspólna Wielokrotność/Największy wspólny dzielnik

W C++

#include <iostream>

using namespace std;

// Funkcja NWD oblicza NWD swoich argumentów
// wykorzystując algorytm Euklidesa
//————————————————-

unsigned NWD(unsigned a, unsigned b)
{
while(a != b) if(a > b) a -= b; else b -= a;
return(a);
}

main()
{
unsigned a,b;
char s[1];

cout << „Obliczanie  NWD  algorytmem  Euklidesa\n”
„————————————–\n”
„Podaj a = „;
cin  >> a;
cout << „\nPodaj b = „;
cin  >> b;
cout << endl;
if((a <= 0) || (b <= 0))
cout << „Zle dane!\n”;
else
cout << „NWD(” << a << „,” << b << „) = ” << NWD(a,b);
}

———————————-

W Javie

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class nwd {

public static int nwd(int a, int b) {

while (a != b ) {
if (a > b)
a = a-b;
else
b = b-a;

}

return a;
}

public static void main(String[] args){

int a = 0;
int b = 0;

String s;

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

System.out.print („Podaj a:”);
try
{
s = stdin.readLine();
a = Math.abs(Integer.parseInt(s));
}
catch(IOException ioex)
{
System.out.println(„Input error”);
System.exit(1);
}
catch ( NumberFormatException e)
{
System.out.println (e.getMessage() + ” nie jest poprawną liczbą całkowitą.”);
System.exit(1);
}

System.out.print („Podaj b:”);
try
{
s = stdin.readLine();
b = Math.abs(Integer.parseInt(s));
}
catch(IOException ioex)
{
System.out.println(„Input error”);
System.exit(1);
}
catch ( NumberFormatException e)
{
System.out.println (e.getMessage() + ” nie jest poprawną liczbą całkowitą.”);
System.exit(1);
}

if (a == 0 || b == 0)

System.out.println („Nie dziel przez zero, cholero”);

else

System.out.println („Największy wspólny dzielnik liczb ” + a + ” i ” + b +” wynosi ” + nwd(a,b));
}

}

——————————————

źródło: http://matematyka.pisz.pl/strona/1350.html

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *