Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.math.BigInteger;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Iterator;
- import java.util.List;
- public class Main
- {
- // Liczba do rozlozenia na czynniki
- public final static BigInteger NUMBER = new BigInteger("10000000");
- // Liczba wątków
- public final static int THREAD_COUNT = Runtime.getRuntime().availableProcessors();
- // Tablica wątków
- public static Thread[] threads = new Thread[THREAD_COUNT];
- // Lista dzielników (czynników pierwszych)
- public static final List<Long> divisorList = Collections.synchronizedList(new ArrayList<Long>());
- private static BigInteger p = BigInteger.ONE;
- public static void main(String[] args)
- {
- System.out.println("Liczba do rozkładu: " + NUMBER);
- System.out.println("Liczba wątków: " + THREAD_COUNT);
- long time = System.nanoTime();
- for(int i = 0; i < THREAD_COUNT; i++)
- {
- final int currentThread = i;
- threads[i] = new Thread()
- {
- @Override
- public void run()
- {
- long remainder = 0;
- long divisionResult = NUMBER.longValue();
- while(multiplyDivisors() != NUMBER.longValue())
- {
- BigInteger currentPrime = nextPrime();
- remainder = 0;
- System.out.println("Wątek " + currentThread + " sprawdza " + currentPrime.longValue());
- while(remainder == 0)
- {
- remainder = divisionResult % currentPrime.longValue();
- if(remainder == 0)
- {
- divisionResult = divisionResult / currentPrime.longValue();
- divisorList.add(currentPrime.longValue());
- }
- }
- }
- stopThreads();
- }
- };
- threads[i].start();
- }
- for(Thread t: threads)
- {
- try
- {
- t.join();
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- System.out.println("Znalezione dzielniki: " + divisorList);
- if(divisorList.size() == 0)
- System.out.println("Podana liczba jest liczbą pierwszą!");
- System.out.println("Czas dzialania programu: " + (System.nanoTime() - time) / 1000000000f + " s");
- }
- @SuppressWarnings("deprecation")
- protected static void stopThreads()
- {
- for(Thread t: threads)
- {
- try
- {
- t.stop();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- protected static long multiplyDivisors()
- {
- long result = 1;
- for(Long n : divisorList)
- result *= n.longValue();
- return result;
- }
- public synchronized static BigInteger nextPrime() {
- p = p.nextProbablePrime();
- return p;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement