Mathime
Mathime

Reputation: 1490

Prime-testing program not working

#include "stdafx.h"
#include "math.h"
#include <string>
#include <iostream>

using namespace std;

int main ()
{
    int x;
    cout << "Enter a number." << endl;
    cin >> x;
    int y = 1;
    int i = 0;
    while (i == 0 && y < sqrtf(x))
    {
        if (fmodf(x,y) == 0)
        {
            i = 1;
        }
        else
        {
            i = 0;
        }
        y++;
    if (i == 1)
    {
        cout << "Your number is prime." << endl;
    }
    else 
    {
        cout << "Your number is composite." << endl;
    }
    }
    return 0;
}

This is a code I created to test for primes. After sorting out several debugging issues I was able to run it.

It opened the command window, read 'Enter a number' and closed itself the second I entered a number.

Help?

Upvotes: 1

Views: 79

Answers (1)

manlio
manlio

Reputation: 18902

You have to:

  • close the while loop in the correct place
  • change the if (i == 1) condition (i==1 means x is divisible by some y)
  • start with y = 2 (every number is divisible by one)
  • include sqrtf(x) in the loop (y <= sqrtf(x) or 15, 25, 35... are primes).

So:

int main()
{
  int x;
  cout << "Enter a number." << endl;
  cin >> x;

  int y = 2;  // <-- changed
  int i = 0;

  while (i == 0 && y <= sqrtf(x))  // <-- changed
  {
    if (fmodf(x,y) == 0)
    {
        i = 1;
    }
    else
    {
        i = 0;
    }

    y++;
  }  // <-- moved here

  if (i == 0)  // <-- changed
  {
    cout << "Your number is prime." << endl;
  }
  else
  {
    cout << "Your number is composite." << endl;
  }

  return 0;
}

works (more or less...).

Anyway:

Somewhat better (but far from perfect):

#include <cmath>
#include <iostream>

int main()
{
  int x;
  std::cout << "Enter a number.\n";
  std::cin >> x;

  int square_root = std::sqrt(x);
  int y = 2;
  int i = 0;
  while (i == 0 && y <= square_root)
  {
    if (x % y == 0)
      i = 1;

    ++y;
  }

  if (i == 0)
    std::cout << "Your number is prime.\n";
  else
    std::cout << "Your number is composite.\n";

  return 0;
}

Now:

Upvotes: 1

Related Questions