So I'm studying c++ from the book ((C++ without fear)). and there's a code I didn't understand. I need to know how the code works. my problem is in the loop, I understand how it works, but I didn't understand how would it work with adding 1 to i. (EVEN WITH COMMENTS).
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n = 0; // Number to test for prime-ness
int i = 2; // Loop counter
bool is_prime = true; // Boolean flag...
// Assume true for now.
// Get a number from the keyboard.
cout << "Enter a number and press ENTER: ";
cin >> n;
// Test for prime by checking for divisibility
// by all whole numbers from 2 to sqrt(n).
while (i <= sqrt(n)) {
if (n % i == 0) { // If i divides n,
is_prime = false; // n is not prime.
}
++i; // Add 1 to i.
}
// Print results
if (is_prime) {
cout << "Number is prime." << endl;
}
else
{
cout << "Number is not prime." << endl;
}
return 0;
}
Adding 1 to i is simply to move on to test the next number the next time round the loop to test if it divides n. ++i is simply the prefix increment operator being invoked. Postfix i++; could be used here for the same effect, as could i = i + 1;, but since there exist some cases where prefix increment is faster than the alternatives (not the case here) it's usually a good habit to use prefix increment always unless you have a specific reason not to do so.
Related
C++
When I first ran this code with a different input value of 881, 643, 743, etc... which are all primes numbers, I got a result of "True" but when I input a higher number like 804047277, it came back as "True" when it should have been "False"
#include <iostream>
int main(){
int num;
std::cin >> num;
for(int i = 2; i < num; i++){
if(num % i == 0){
std::cout << "True" << std::endl;
break;
}
else{
std::cout << "False" << std::endl;
break;
}
}
return 0;
}
I corrected my code (The code below) and received the correct answer, which was "False"
#include <iostream>
int main(){
int num;
std::cin >> num;
for(int i = 2; i < num; i++){
if(num % i == 0){
std::cout << "True" << std::endl;
break;
return 0;
}
else{
std::cout << "False" << std::endl;
break;
}
}
return 0;
}
Shouldn't the break in the if statement stop the loop overall? I am just trying to understand why the break wasn't good enough, and I had to return 0;
I would correct your code like following (see description afterwards):
Try it online!
#include <iostream>
int main() {
int num = 0;
std::cin >> num;
for (int i = 2; i < num; ++i)
if (num % i == 0) {
std::cout << "True (Composite)" << std::endl;
return 0;
}
std::cout << "False (Prime)" << std::endl;
return 0;
}
Input:
804047277
Output:
True (Composite)
As it is easy to understand, your program is intended to check primality and compositness of a number.
Mistake in your program is that you show False (Prime) when division by a very first i gives non-zero remainder. Instead, to actually check primality, you need to divide by all possible i and only if ALL of them give non-zero, then number is prime. It means that you shouldn't break or show False on very first non-zero remainder.
If ANY of i gives zero remainder then given number by definition is composite. So unlike the Prime case, this Composite case should break (or return) on very first occurance of zero remainder.
In code above on very first zero remainder I finish program showing to console that number is composite (True).
And only if whole loop finishes (all possible divisors are tested) then I show False (that number is prime).
Regarding question if break; is enough to finish a loop, then Yes, after break loop finishes and you don't need to return 0; after break, this return statement never finishes.
Also it is well known fact that it is enough to check divisibility until divisor equal to Sqrt(num), which will be much faster. So your loop for (int i = 2; i < num; ++i) should become for (int i = 2; i * i <= num; ++i) which is square times faster.
I've recently (very, very recently) have gotten into programming in C++. I'm writing a program to find the highest prime number below prime. However, when I execute the code, nothing is displayed, and in the console it says this:
Process returned -1 (0xFFFFFFFF) execution time : 0.409 s
Press ENTER to continue.
I've tried some debugging, and I've figured out the problematic section is lines 17-19 (the if statement), but I can't figure out what I'm doing wrong.
C++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//cout << "maybe here?";
int prime = 1000;
//cout << "here";
while(true){
//cout << "here2";
int testr = ceil(sqrt(prime));
cout << testr;
bool isprime = true;
for(int i = 0; i < testr; i++){
cout << i << " ";
if(testr % i == 0){
isprime = false;
}
}
if(isprime){
break;
}else{
prime--;
}
}
cout << prime;
}
Any and all help is appreciated! Thanks!
Additional Info:
I'm using Code::Blocks on Mac OSX 64 bit. I'm used to programming in Java, so it may just be a C++ thing I'm unaware of.
Quite a few issues.
1) The answer to your question "find the lowest prime number below prime" is 2, no programming required.
2) Assuming you want to find the greatest prime number below prime, you should test all numbers from prime - 1, downwards.
3) The very first iteration of your loop:
for(int i = 0; i < testr; i++){
cout << i << " ";
if(testr % i == 0){
will cause an exception: division by 0.
The reason is that you are trying to divide by 0 in your for loop you should begin with 2. Take a look at this one, it's optimal I guess.
bool isPrime(int n) {
if(n<2)
return false;
for(int i=2;i*i<=n;i++)
if(n%i==0)
return false;
return true;
}
I'm struggling to apply a "While" loop to the following problem: Design the logic for a program that allows a user to enter a number. Display the sum of every number from one through the entered number.
Start
int userNumber;
Declarations
int number = 1
while number <= userNumber
++number
endwhile
output number
Stop
I know my code isn't correct as it is just adding one to the initial value until the user's number is reached, thus making the output the user's number. How would I go about adding each subsequent value without writing them out e.g. user's number is 10, so the program would add 1+2+3+4+5+6+7+8+9+10 and output the total of 55?
Thank you!
Here's a tip. You'll want to start at the users number and count down to 0. Like this:
int finalNum = 0;
int userNum;
//This is where you need to get the user's number....
while(userNum > 0)
{
finalNum += userNum;
userNum--;
}
//Do whatever you need to finalNum....
EDIT: It appears you've posted pseudocode; usually a big no-no here unless stated otherwise. It's better to post the actual code as it's easier to tell what exactly is going on.
The function you need could look like this for c++:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
unsigned t = 0; // Assume the result to be 0 (zero)
for (i = 1; i <= x; i++) // Continue until i is greater than x
{
t += i; // Accumulate, i.e. t = t +i
}
cout << "sum=" << t << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
An alternative is:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
cout << "sum=" << (x*(x+1)/2) << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
This works because the sum of all integers from 1 to n is n*(n+1)/2
I am unsure what the fault in my logic is. Sample output:
How many terms of the Fibonacci Sequence do you wish to compute?
1
1
1
--How many terms of the Fibonacci Sequence do you wish to compute?
5
5
5
5
5
5
5
Why is it doing this?
// Recursive Fibonacci Sequence
#include <iostream>
using namespace std;
double fib(double number);
int main(void) {
double number;
cout << "How many terms of the Fibonacci Sequence do you wish to compute?" << endl;
cin >> number;
for(int i = 0; i <= number; ++i)
cout << fib(number) << endl;
} // end main
// function fib definition
double fib(double number) {
if((number == 0) || (number == 1))
return number;
else
return fib(number - 1) + fib(number - 2);
} // end function fib
Look at your loop:
for(int i = 0; i <= number; ++i)
cout << fib(number) << endl;
Notice how the body of the loop doesn't use i... it always calls fib(number). Changing that to fib(i) will fix it.
(It's not terribly efficient, in that you'll end up recalculating values each time, but that's a separate matter. While you could put the printing in fib, that mixes the concerns of "what to do with the results" and "computing the Fibonacci sequence".)
You should just pass 'i' as the parameter in your for loop not 'number'
Make it:
for(int i = 0; i <= number; ++i)
cout << fib(i) << endl;
I need some help revising this. It keeps only displaying 0s as the temp. Thank you.
// A program to determine whether the input number is a perfect number
// A perfect number is defined by the sum of all its positive divisors excluding itself
// 28: 1+2+3+7+14 = 28.
int perfect, limit, divisor;
cout << "Please enter a positive integer in order to define whether it is a perfect integer or not: " ;
cin >> perfect;
cout << endl;
int temp = 0;
int prevtemp = 0;
limit = 1;
divisor = 1;
while (limit < perfect)
{
if ((perfect % divisor) == 0)
{
divisor = prevtemp;
temp = prevtemp + temp;
}
limit++;
divisor++;
}
if (perfect == temp)
cout << "Your number is a perfect number!" << endl;
else
cout << "Your number is not a perfect number" << endl;
return 0;
You are never setting prevtemp to anything other than 0, so adding it to temp does nothing.
I believe you meant to say
if ((perfect % divisor) == 0)
temp += divisor; // not "divisor = prevtemp;"
The line "temp = prevtemp + temp" should also be removed with this solution; there is no longer any need for the prevtemp variable.
Also, there is no need to keep separate limit and divisor variables, since they are always the same. Just remove limit and change the loop condition to use divisor.
Also, as Mark Byers pointed out, the loop would be simpler to understand if you refactored it into a for loop rather than a while.
It seems like you are making it too complicated. Here's how you could do it:
int total = 0;
for (int i = 1; i < perfect; ++i)
{
if (perfect % i == 0)
total += i;
}
if (perfect == total)
cout << "Your number is a perfect number!" << endl;
else
cout << "Your number is not a perfect number" << endl;
Note that the running total is kept in a variable called total (you called this variable temp) and it is only increased when the number is an exact divisor.
I'm not sure, but I'd guess that in the code:
if ((perfect % divisor) == 0)
divisor = prevtemp;
you intended this to be prevtemp=divisor instead. That fixes an obvious problem, but still leaves quite a bit that doesn't look like it's doing that you probably intended. For example, I can't quite figure out what limit is intended to accomplish -- you initialize it and increment it, but as far as I can see, you never use its value (well, I guess you use it, but its value is always the same as divisor's so I'm not sure why you think you need both, or how limit makes any sense as its name).
Edit: It would make sense to have a limit. In particular, factors always come in pairs: one that's less than or equal to the square root of the number, and one that matches the first that's always greater than or equal to the square root of the number. As such, you don't need to scan all the way up to the number itself looking for factors -- you can set the square root of the number as the limit, and scan only up to that point. For each factor you find up to that point, the matching factor will be perfect/divisor. Since you've already gotten one working example, I guess I might as well just hope this isn't homework, and post an example as well:
bool is_perfect(int number) {
int limit = sqrt((double)number);
int sum = 1;
for (int i=2; i<=limit; i++)
if (number % i == 0)
sum += i + number/i;
return sum == number;
}
You are never assigning anything to prevtemp after initializing it to 0, so there is nothing to add to temp on the line that reads temp = prevtemp + temp.
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
int n,i=1,sum=0;
cout<<"Enter a number: ";
cin >> n;
while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
cout << i << " is a perfect number";
else
cout << i << " is not a perfect number";
system("pause");
return 0;
}