You are here:

C++/Program to determine prime numbers

Advertisement


Question
Write a program that can be used to determine whether a number is a prime number or not. implement it using Classes.

Answer
Hello moses, thank you for the question.

Why you would use a class for this, I'm not sure, so I didn't bother when I was figuring it out. If you want you can place this function in a singleton math class of some sort if you need to. The was a tricky one, but this function should help you out:

#include <cmath>

bool IsPrime(int num)
{
// no number can divide into 0
if(num == 0)
return true;

// make sure its not negative
num = abs(num);

for(int i = 2; i <= sqrt(num); i++)
if(num % i == 0)
return false;
  
return true;   
}

That should do it. Please don't hesitate to ask another question if you have one.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.