0

The question is as follow :

Write a program that prompts the user to enter a positive integer m that represents the sum of all page numbers in a book. The program prints whether the number is a valid sum or not. For example, the integer 21 is a valid sum of page numbers because 1 + 2 + 3 + 4 + 5 + 6 = 21. The integer 25 is not a valid sum because the sum of the first 6 page numbers is 21 and the next page number is 7, so the sum of the first 7 page numbers should be 28. If m is a valid sum of all page numbers, then there must be an integer n such that 1+2+3+ … + n = n(n+1)/2 = m

Here's my code:

#include <iostream>
using namespace std;
int main() {
    int num,n=0,sum=0;
    cout<<"Enter a positive integer"<<endl;
    cin>>num;

    for (int i=1;i<num;i++){
        sum+=i;
        n++;
        if (sum==num)
            break;
 }
        if (((n*(n+1))/2)==num){
            cout<<"This number is valid";

        }
        else{
            cout<<"This number is invalid";

        }


}

The code is working but I need another way to implement this program without using loops but only selection statements.Is it possible to do that??

Seba
  • 21
  • 8
  • *sighes* https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – SuperStormer Feb 20 '21 at 19:26
  • You are basically asking how to test if `num` is a [triangular number](https://en.wikipedia.org/wiki/Triangular_number). You can search on Stack Overflow or the internet for "test triangular number" to get answers. – Blastfurnace Feb 20 '21 at 20:01

1 Answers1

1

Rearrange the equation slightly:

n(n+1)/2 = m
n(n+1) = 2m

Now, for this equation to be true, sqrt(2m) has to be between n and n+1, meaning n = floor(sqrt(2m)) and n+1 = ceil(sqrt(2m)). Then you can just check that the calculated values for n and n+1 multiply to 2m. This is simple to check using code:

#include <iostream>
#include <cmath>

int main(){
    int num;
    std::cout << "Enter a positive integer\n";
    std::cin >> num;
    float a = std::sqrt(2 * num);
    if(std::floor(a) * std::ceil(a) == 2 * num){
        std::cout << "This number is valid\n";
    } else{
        std::cout << "This number is invalid\n";
    }
}

Note that I cleaned up your code slightly. For more info, checkout Why is "using namespace std;" considered bad practice? and "std::endl" vs "\n".

SuperStormer
  • 4,997
  • 5
  • 25
  • 35