logical error in perfect number program - c++

I was wondering how to develop a C++ program that prompts the user for 2 numbers n1, n2 with n2 being greater than n1. Then the program is meant to determine all the perfect numbers between n1 and n2. An integer is said to be a perfect number if the sum of its factors, including 1 (but not the number itself), is equal to the number itself. For example, 6 is a perfect number because 6 = 1 + 2 + 3.
so far here is what I have come up with, and it has no runtime/syntax errors, but unfortunately logical error(s):
#include <iostream>
using namespace std;
int main(){
int number, sum = 0, divi = 1, n1, n2;
cout<<" Please enter n1: ";
cin>>n1;
cout<<" Please enter n2: ";
cin>>n2;
number = n1;
while(number <= n2){
while(divi <=n2){
if (number%divi ==0)
sum+=divi;
divi++;
}
if(sum == number)
cout<<number<<endl;
number++;
}
return 0;
}
I can only use while loops. Can you spot any logical errors?

You need to reset divi to 1 and sum to 0 just after the line while(number <= n2){. (Otherwise divi and sum will grow in error).
Redefine the upper bound of your inner while to while(divi < number){. (You want to examine the factors between 1 and number, not after it.)

#include <iostream>
using namespace std;
int main(){
int number, sum = 0, divi = 1, n1, n2;
cout<<" Please enter n1: ";
cin>>n1;
cout<<" Please enter n2: ";
cin>>n2;
number = n1;
while(number <= n2){
sum=0; // reintialize variable for every incrasing number n1 to n2
divi=1; // reintialize variable
while(divi <number){ //use number insteaed of n2
if (number%divi ==0)
{
sum+=divi;
}
divi++;
}
if(sum == number)
cout<<number<<endl;
number++;
}
return 0;
}

Related

I want to know the error in my code. This is to print sum of all even numbers till 1 to N

#include<iostream>
using namespace std;
int main(){
int i = 1;
int sum;
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
cout << sum;
}
This is to print the sum of all even numbers till 1 to N.
As I try to run the code, I am being asked the value of N but nothing is being printed ahead.
For starters the variable sum is not initialized.
Secondly you need to increase the variable i also when it is an even number. So the loop should look at least like
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1;
}
In general it is always better to declare variables in minimum scopes where they are used.
So instead of the while loop it is better to use a for loop as for example
for ( int i = 1; i++ < N; ++i )
{
if ( i % 2 == 0 ) sum += i;
}
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
Let's step through this. Imagine we're on the loop where i = 2 and you've entered N = 5. In that case...
while(i <= N)
2 <= 5 is true, so we loop
if(i%2 == 0)
2 % 2 == 0 is true, so we enter this branch
sum = sum + i;
Update sum, then head back to the top of the loop
while(i <= N)
Neither i nor N have changed, so 2 <= 5 is still true. We still loop
if(i%2 == 0)
2 % 2 == 0 is still true, so we enter this branch again...
Do you see what's happening here? Since neither i nor N are updated, you'll continue entering the same branch and looping indefinitely. Can you think of a way to prevent this? What would need to change?
Also note that int sum; means that sum will have a garbage value (it's uninitialized). If you want it to start at 0, you'll need to change that to
int sum = 0;
You're looping infinitly when i is even because you don't increase it.
Better option would be this if you want to use that while loop :
while(i<=N)
{
if(i%2 == 0)
sum = sum + i;
i=i+1;
}
cout << sum;
If you don't need to do anything when the condition is false, just don't use an else.
No loops are necessary and sum can be evaluated at compile time if needed too
// use unsigned, the whole excercise is pointless for negative numbers
// use const parameter, is not intended to be changed
// constexpr is not needed, but allows for compile time evaluation (constexpr all the things)
// return type can be automatically deduced
constexpr auto sum_of_even_numbers_smaller_then(const unsigned int n)
{
unsigned int m = (n / 2);
return m * (m + 1);
}
int main()
{
// compile time checking of the function
static_assert(sum_of_even_numbers_smaller_then(0) == 0);
static_assert(sum_of_even_numbers_smaller_then(1) == 0);
static_assert(sum_of_even_numbers_smaller_then(2) == 2);
static_assert(sum_of_even_numbers_smaller_then(3) == 2);
static_assert(sum_of_even_numbers_smaller_then(7) == 12);
static_assert(sum_of_even_numbers_smaller_then(8) == 20);
return 0;
}
int main(){
int input; //stores the user entered number
int sum=0; //stroes the sum of all even numbers
repeat:
cout<<"Please enter any integer bigger than one: ";
cin>>input;
if(input<1) //this check the number to be bigger than one means must be positive integer.
goto repeat; // if the user enter the number less than one it is repeating the entry.
for(int i=input; i>0; i--){ // find all even number from your number till one and than totals it.
if(i%2==0){
sum=sum+i;
int j=0;
j=j+1;
cout<<"Number is: "<<i<<endl;
}
}
cout<<endl<<"The sum of all even numbers is: "<<sum<<endl;}
Copy this C++ code and run it, it will solve your problem.
There are 2 problems with your program.
Mistake 1
The variable sum has not been initialized. This means that it has(holds) an indeterminate value. And using this uninitialized variable like you did when you wrote sum = sum + i; is undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has undefined behavior.
This is why it is advised that:
always initialize built in types in local/block scope.
Mistake 2
The second problem is that you're not updating the value of variable i.
Solution
You can solve these problems as shown below:
int main(){
int i = 1;
int sum = 0; //INITIALIZE variable sum to 0
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1; //update(increase i)
}
cout << sum;
}
1For more reading(technical definition of) on undefined behavior you can refer to undefined behavior's documentation which mentions that: there are no restrictions on the behavior of the program.

C++ Gapful Numbers Crashing

I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?
Here's my code:
#include<math.h>
#include<stdlib.h>
using namespace std;
void gapful(int);
bool gapCheck(int);
int main(){
int n;
cout<<"Enter a top number: ";
cin>>n;
gapful(n);
system("pause");
return 0;
}
void gapful(int og){
for(int i=0; i<=og; i++){
fflush(stdin);
if(gapCheck(i)){
cout<<i<<" ";
}
}
}
bool gapCheck(int n){
int digits=0;
int n_save,n1,n2,n3;
if(n<100){
return false;
}
else{
n_save=n;
while(n>10){
n/=10;
digits++;
}
digits++;
n=n_save;
n1=n/pow(10, digits);
n2=n%10;
n3=n1*10 + n2;
if(n%n3 == 0){
return true;
}
else{
return false;
}
}
}
I'm open to any suggestions and comments, thank you. :)
For n == 110, you compute digits == 3. Then n1 == 110 / 1000 == 0, n2 == 110 % 10 == 0, n3 == 0*10 + 0 == 0, and finally n%n3 exhibits undefined behavior by way of division by zero.
You would benefit from more functions. Breaking things down into minimal blocks of code which represent a single purpose makes debugging code much easier. You need to ask yourself, what is a gapful number. It is a number that is evenly divisible by its first and last digit. So, what do we need to solve this?
We need to know how many digits a number has.
We need to know the first digit and the last digit of the number.
So start out by creating a function to resolve those problems. Then, you would have an easier time figuring out the final solution.
#include<math.h>
#include <iostream>
using namespace std;
void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);
int main(){
int n;
cout<<"Enter a top number: " << endl;
cin>>n;
gapful(n);
return 0;
}
void gapful(int og){
for(int i=1; i<=og; ++i){
if(gapCheck(i)){
cout<<i << '-' <<endl;
}
}
}
int getDigits(int number) {
int digitCount = 0;
while (number >= 10) {
++digitCount;
number /= 10;
}
return ++digitCount;
}
int digitAt(int number,int digit) {
int numOfDigits = getDigits(number);
int curDigit = 0;
if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
while (numOfDigits != digit) { //Count back to the digit requested
number /=10;
numOfDigits -=1;
}
curDigit = number%10; //Get the current digit to be returned.
} else {
throw "Digit requested is out of range!";
}
return curDigit;
}
bool gapCheck(int n){
int digitsN = getDigits(n);
if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
return false;
}
int first = digitAt(n,1) * 10; //Get the first number in the 10s place
int second = digitAt(n,digitsN); //Get the second number
int total = first + second; //Add them
return n % total == 0; //Return whether it evenly divides
}

How can i program a recursive coin change in c++?

I'm trying to build a recursive call for coin change in c++ . i tried most of the algorithm on the internet but it doesn't seem to apply with vector or it doesn't out the sums of the coin used. Can anyone help me understand what the recursive function has to call? So my algorithm doesn't give me the minimum number of coin used and i don't know how to save the coin used.
int coin(vector<int> denom, int s,int N)
{
if(N == 0)
{
return 1;
}
if(N < 0 || (N > 0 && s < 0))
{
return 0;
}
return min(coin(denom,s - 1, N), 1 + coin(denom, s,N-denom[s-1]));
}
Input a value N:
Input: 40
Input how many denominations:
Input: 3
Denominations #1:
Input: 5
Denominations #2:
Input: 20
Denominations #3:
Input: 30
Output:
Minimum # of coins: 2
Coin used: 20 + 20
Don't want: 30 + 5 + 5
Some points to consider:
Firstly, there is no need to send the number of denominations i.e. s
as an argument to the coin method as long as a vector is being used, because vector has inbuilt size() method which does that job for us.
Secondly, to save the solution you need another vector of int named solution, but this vector is just to keep a record and has nothing to do with the actual recursive implementation and hence, it is defined as a global variable. Alternatively, you could pass it as an argument by reference to the coin method too.
Thirdly, the denominations entered by the user should be sorted before passing them to the coin method. For this, I have used the sort method from the algorithm library.
What the recursive algorithm basically does is:
At each step, it considers the largest denomination d (last element in the sorted denomination vector denom like denom[denom.size() - 1]) which is then removed from the vector using pop_back method of vector.
Using d we find count_d, which is the number of coins of denomination d, used in the solution. We get this by simply applying a div operation like N/d, which gives the Quotient.
Then d is added to the vector solution, count_d number of times.
The recursive call, adds count_d from this iteration and recalls coin with the reduced denominations vector denom and Remainder of the amount N using N%d.
See Quotient and Remainder for clarity of what div / and mod % operators do.
Here is the code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution;
int coin(vector<int> denom, int N)
{
if(N <= 0 || denom.size() <= 0)
{
return 0;
}
int d = denom[denom.size() - 1];
denom.pop_back();
int count_d = N/d;
solution.insert(solution.end(), count_d, d);
return count_d + coin(denom, N%d);
}
int main()
{
int N,s;
cout<<"Input a value N:\nInput: ";
cin>>N;
cout<<"Input how many denominations:\nInput: ";
cin>>s;
vector<int> denom;
for(int i = 0; i < s; i++)
{
int d;
cout<<"Denominations #"<<i+1<<":\nInput: ";
cin>>d;
denom.push_back(d);
}
std::sort(denom.begin(), denom.end());
int minNoOfCoins = coin(denom, N);
cout<<"\nOutput:\nMinimum # of coins: "<<minNoOfCoins;
if(minNoOfCoins > 0)
{
cout<<"\nCoins used: ";
for(int i = 0; i < solution.size(); i++)
{
if(i > 0)
{
cout<<" + ";
}
cout<<solution[i];
}
}
cout<<endl;
system("pause");
}

Greatest Common Divisor using Euclidian Algorithm?

So I'm having a problem with my code here.
I am coding a Greatest Common Divisor using the Euclidian Algorithm and I can't seem to utilize the loop in order to keep the division to keep repeating until I get the greatest common divisor. So for now, I am able to get the remainder but do not know how to go on from there basically.
Any help will be greatly appreciated!
Here is what I have so far
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int a;//Holds the first number
int b;//Holds the second number
int temp;//Assign to greatest number
int hold;//Assign to smaller number
float euclid;//soon to be function?
int leftover;
float gcd;
int main ()
{
cout<<"Welcome to Brian Garnadi's Version of GCD!\n"<<endl;
cout<<"Enter the first integer to be calculated: ";
cin>> a;
cout<<"Now enter the second integer: ";
cin>>b;
if (a>b)//Determines bigger number
{temp=a;
hold=b;
}
if (a<b)//Determines smaller number
{
temp=b;
hold=a;
}
leftover= temp%hold;
cout<<"\nThe remainder of the two numbers divided is "<<leftover<<".\n"<<endl;
}
Actually there is no need to calculate bigger number the euclid's algorithm manages itself.
Here's the working code :
#include <iostream>
using namespace std;
int gcd(int m,int n)
{
if(n == 0)
return m;
return gcd(n, m % n);
}
int main()
{
int a,b,answer;
cout<<"Welcome to Brian Garnadi's Version of GCD!\n"<<endl;
cout<<"Enter the first integer to be calculated: ";
cin>> a;
cout<<"Now enter the second integer: ";
cin>>b;
answer = gcd(a,b);
cout << "The GCD of the two numbers is : " << answer << endl;
return 0;
}
Do not forget to handle negative numbers in algorithm.
gcd(m, n) = gcd(n, m%n) when n != 0
= m when n = 0
function:
int gcd(int m, int n) {
if(m == 0 && n == 0)
return -1;
if(m < 0) m = -m;
if(n < 0) n = -n;
int r;
while(n) {
r = m % n;
m = n;
n = r;
}
return m;
}

Prime Number assignment basic c++

Here is my assignment:
A prime number is a number greater than 1 which is only evenly divisible by 1 and itself. For this assignment you will find which numbers from 2 to n (where n is a user-specified number) are prime.
Ask the user for a number, n, greater than 2. Keep asking for a number until a number greater than 2 is provided. Assume that the user will only enter numbers (that is, you do not need to check if a user enters text).
Use a loop to iterate on a variable, i, from 2 through n. For each iteration, check all numbers from 2 through i to determine whether the number is prime. If it is prime, print out i and the word "Prime".
Use the modulus operator, %, to determine if a number is prime
Here is what I have so far. It doesnt work. And I dont know why. please help, im a business student taking basic programming as an elective.
#include <iostream>
using namespace std;
int main()
{
int n;
int i;
int x;
while (n<=2)
{
cout << "Enter a number greater then 2: \n";
cin >> n;
for (x=n; x>=2; x--)
{
bool prime = false;
for (i=2; i<x; i++)
{
if (x%i==0)
{
prime = true;
}
}
if (prime==false)
{
cout << x << " Prime.\n";
}
}
}
return 0;
}
I didn't actually used your code because of indentication it was little bit of hard to read. But I wrote a new method for you. I suggest always divide your code into methods to make it more managable. You can call this in your main method
bool checkPrime(int number)
{ // input: num an integer > 1
// Returns: true if num is prime
// false otherwise.
int i;
for (i=2; i<number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
And here is how can you call this method in the main:
int main()
{
int number;
cout << "Enter an integer (>1): ";
cin >> number;
if (checkPrime(number))
{
cout << number << " is prime." << endl;
}
else
{
cout << number << " is not prime." << endl;
}
// I think this is more convention than anything.
return 0;
}
It may not be the optimal program out there, but this should work:
#include <iostream>
using namespace std;
int main()
{
int n;
int i;
int x;
cout << "Enter a number greater then 2: \n";
cin >> n;
while (n<=2)
{
cout << "Enter a number greater then 2: \n";
cin >> n;
}
for (x=n; x>=2; --x)
{
for (i=2; i<x; ++i)
{
bool prime = true;
for (j=2; j<i/2; ++j)
{
if (i%j==0)
{
prime = false;
break;
}
}
if (prime)
{
cout << j << " Prime.\n";
}
}
}
return 0;
}
There are two easy means to go faster: first there is no need to test potential divisors that are too big (as pointed out by arne), and second, there is no need to test even numbers except 2.
Something like this:
#include <cassert>
bool is_prime(unsigned n)
{
if (n == 2)
return true;
if (n <= 1
|| n % 2 == 0)
return false;
for (int d = 3; d * d < n; ++d)
if (n % d == 0)
return false;
return true;
}
int main()
{
assert(!is_prime(0));
assert(!is_prime(1));
assert(is_prime(2));
assert(is_prime(3));
assert(!is_prime(4));
assert(is_prime(5));
assert(!is_prime(6));
assert(!is_prime(256));
assert(is_prime(257));
}
Of course, even faster is building a table of primes, and using this table as potential divisors, instead of every odd number. Makes sense if you have several numbers to check.
Please, say, why it let say you it does not work? Among others I get this output.
Enter a number greater then 2:
100
97 Prime.
89 Prime.
83 Prime.
79 Prime.
73 Prime.
71 Prime.
67 Prime.
61 Prime.
59 Prime.
53 Prime.
47 Prime.
43 Prime.
41 Prime.
37 Prime.
31 Prime.
29 Prime.
23 Prime.
19 Prime.
17 Prime.
13 Prime.
11 Prime.
7 Prime.
5 Prime.
3 Prime.
2 Prime.
But as int n; leaves n uninitialized, the while loop might not be entered.
I think the Answer 1 function checkprime(int number) can improved but purely on preformance basis, consider the fact that prime numbers cannot be even.So if add an extra check to see if (number % 2 == 0) will reduce a lot of iteration of the for loop, and for the remaining i think iterating the loop from 2 to 9 is enough rather than 2 to n. Too many iterations will slow you down on larger numbers.