#include #include #include "MainWindow.h" #include "ui_MainWindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } #include void MainWindow::on_lineEditNumber_textEdited(const QString &arg1) { // std::cout << qPrintable(arg1) << std::endl; bool enable = arg1.trimmed().length() > 0; this->ui->pushButtonCalculate->setEnabled(enable); } void MainWindow::on_pushButtonStop_clicked() { this->userStopped = true; } void MainWindow::on_pushButtonCalculate_clicked() { bool isValid = true; const QString& text = this->ui->lineEditNumber->text(); long long int number = text.toLongLong(&isValid); if ( isValid ) { this->ui->plainTextEditResults->clear(); this->ui->pushButtonCalculate->setEnabled(false); this->ui->pushButtonStop->setEnabled(true); this->userStopped = false; ui->statusBar->showMessage( tr("Calculating...") ); QTime time; time.start(); long long sumCount = this->calculate(number); double seconds = time.elapsed() / 1000.0; this->ui->pushButtonCalculate->setEnabled(true); this->ui->pushButtonStop->setEnabled(false); ui->statusBar->showMessage( tr("%1 sums found in %2 seconds").arg(sumCount).arg(seconds) ); } else { ui->statusBar->showMessage( tr("Invalid number: %1").arg(text) ); } } long long MainWindow::calculate(long long number) { if ( number < 4 || number == 5 ) return 0; return number % 2 == 0 ? calculateEvenGoldbach(number) : calculateOddGoldbach(number); } long long MainWindow::calculateEvenGoldbach(long long number) { long long results = 0; for ( long long a = 2; a < number && this->userStopped == false; ++a ) { if ( ! isPrime(a) ) continue; long long b = number - a; if ( b >= a && isPrime(b) ) this->ui->plainTextEditResults->appendPlainText( tr("%1: %2 + %3").arg(++results).arg(a).arg(b) ); QApplication::processEvents(); } return results; } long long MainWindow::calculateOddGoldbach(long long number) { long long results = 0; for ( long long a = 2; a < number; ++a ) { if ( ! isPrime(a) ) continue; for ( long long b = a; b < number; ++b ) { if ( this->userStopped ) return results; if ( ! isPrime(b) ) continue; long long c = number - a - b; if ( c >= b && isPrime(c) ) this->ui->plainTextEditResults->appendPlainText( tr("%1: %2 + %3 + %4").arg(++results).arg(a).arg(b).arg(c) ); QApplication::processEvents(); } } return results; } bool MainWindow::isPrime(long long number) { if ( number < 2 ) return false; long long last = static_cast( qSqrt( number) ); for ( long long i = 2; i <= last; ++i ) if ( number % i == 0 ) return false; return true; }