473,594 Members | 2,770 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Understanding the 'Prime Number Test' code.

2 New Member
Hello everybody,

I have just recently started learning C++ and I have come across my first hurdle. I have read, and re-read, researched online, but to no avail: I'm unable to comprehend how the code works and why it does. If someone would be kind enough to explain each step of the code, the reason it's there, the function of the statement, etc. it would be immensely appreciated!

Cheers,
Apprentice01 (Using Dev-C++ on WinXP)

#include <iostream>
#include <math.h>
using namespace std;

int main(){
int n, i, is_prime;

is_prime = true;

cout << "Enter a number to test primeness: ";
cin >> n;

i = 2;
while (i <= sqrt(static_cas t<double>(n))) {
if (n % i == 0)
is_prime = false;
i++;
}

if (is_prime)
cout << "Number is prime.";
else
cout << "Number is not prime.";
return 0;
}
Nov 15 '07 #1
2 3037
Ganon11
3,652 Recognized Expert Specialist
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <math.h>
  3. using namespace std;
  4.  
  5. int main(){
  6.    int n, i, is_prime;
  7.  
  8.    is_prime = true;
  9.  
  10.    cout << "Enter a number to test primeness: ";
  11.    cin >> n;
  12.  
  13.    i = 2;
  14.    while (i <= sqrt(static_cast<double>(n))){
  15.       if (n % i == 0)
  16.          is_prime = false;
  17.       i++;
  18.    }
  19.  
  20.    if (is_prime)
  21.       cout << "Number is prime.";
  22.    else
  23.       cout << "Number is not prime.";
  24.    return 0;
  25. }
OK, I'll assume you know what all the variable declarations are about, so I'll skip to the while loop.

A number is prime if its only divisors are 1 and itself (because, for any number N, N/1 == N and N/N == 1. If a number m is a divisor of n, that means there exists an integer c such that m * c == n (For example, 5 is a divisor of 15 because 3 * 5 == 15. n is 15, m is 5, and c is 3 in this example). The largest number that could possibly be a divisor of n is the square root of n (because any larger than this multiplied by an integer is either less than n (if c == 1) or greater than n (for c > 1). So you only need to check from 2 to sqrt(n) for divisors.

This is exactly what your loop does. It checks if i is a divisor of n by seeing if the remainder after integer division is 0 (that's the % statement). It also makes i all values between 2 and sqrt(n). If there is ever a number i that divides evenly into n (i.e. n % i == 0), then i is a divisor of n. Since i cannot be 1 (we start at 2 and increase) and i cannot be n (we stop at sqrt(n) < n), n cannot be prime.

Anything else you're not getting? This is mostly mathematics, not programming.
Nov 15 '07 #2
apprentice01
2 New Member
Thank you for the explanation! Will pursue my studies with the new light that has been shed!
Nov 16 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

9
2698
by: Greg Brunet | last post by:
In doing some testing of different but simple algorithms for getting a list of prime numbers, I ended up getting some results that seem a bit contradictory. Given the following test program (testPrimes.py) with two algorithms that both check for primes by testing only odd numbers using factors up to the square root of the value, where Primes1 is based on all of the existing primes so far, and Primes2 is based on all odd numbers, I would...
5
2713
by: Rahul | last post by:
HI. Python , with its support of arbit precision integers, can be great for number theory. So i tried writing a program for testing whether a number is prime or not. But then found my function painfully slow.Here is the function : from math import sqrt def isPrime(x): if x%2==0 or x%3==0: return 0
11
7148
by: don | last post by:
Ok, this is a homework assignment, but can you help me out anyway...... I need a routine for figuring out if a number inputted by the user is a prime number or not...... all I'm asking for is Not the exact code ( well maybe a little) but the logic or algorithm to tell whether or not a number is prime....
0
2395
by: AshifToday | last post by:
this was my and my frineds little project in earlier classes, the program seperates the composite and prime numbers in two sections of the screen ===================== /* This program has been made by A & A Group. Muhammad Ali: Roll # 1462 Class A-2 , B.Sc.(Hons.) in C.S.
20
6803
by: Tuvas | last post by:
I have made and recently posted a libary I made to do Modular Arithmetic and Prime numbers on my website at http://www.geocities.com/brp13/Python/index.html . I am currently in a crypotology class, and am working on building a RSA public key cryptology system for a class project. I am building the librarys just to get the experience to do so. However, I would ask if any of you know of any gaping security holes that can easily be seen from...
3
3833
by: triplejump24 | last post by:
Hey. Im trying to make program that basically displays all the prime numbers. I need to use bool and for but im not quite sure if i have this right. So far i have this bunch of a mess but can anyone point me in the right direction? Thanks! # include <iostream> # include <cmath> using namespace std; int i; //int sqrt;
4
5214
by: SweetLeftFoot | last post by:
Hello, i have designed some code that works out the first 250 prime numbers and prints them to the screen. However i need to implement 2 functions, one of which returns a 1 if the number is a prime and 0 if it isn't. I have spent ages just getting this code to work and i'm worried i need to rip it to bit to get this function to work ! The function is: int prime(int number) here is my code so far: #include...
60
1950
by: rhle.freak | last post by:
Here is my code to generate prime numbers.It works absolutely fine when the range is *not very large*. However on initializing i with a large integer it produces erroneous results (some numbers ending in 5 ..which obviously cannot be prime numbers) can anyone please help me out with the reason?? /*Generate Prime Numbers*/ #include<stdio.h>
0
7936
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7874
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7997
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6646
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5402
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2383
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1469
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.