Click here to Skip to main content
15,944,136 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hello help simple output program..
when the int very large is error..
is there a better solution?
like
n = 1000000000000
k = 1000000000001
this will be error

What I have tried:

long long n;
  long long k;
	unsigned int count = 0;
	cin >> n >> k;
	for(int i = 1; i <= n; i++)
	{
		for(int y = i+1; y <= n; y++)
		{
			if(i + y == k)
			{
				count = count + 1;
			}
		}
	}
	cout << count << endl;
	return 0;
Posted
Updated 17-Aug-18 10:08am
v2

On most platforms the C/C++ type unsigned int is 32-bit wide. That means the max. decimal value is 4,294,967,295 which is less than 1,000,000,000,000.

If you need larger values use 64 bit values: unsigned long long or uint64_t (include cstdint with C++11 or stdint.h).
 
Share this answer
 
You used the long long type for n and k and it also needs to be used for i, y, and k because, as Jochen wrote, the limit for count will be reached before it is reached for n and k.
 
Share this answer
 
You know that there is different types of integers, different sizes.
You need to be consistent, you can't have n and k as long long type and expect to use ints as counters with n as the loop limit.

The 2 nested loops are very simple minded, and thus brute force.
Take a sheet of paper and a pencil and solve the problem with small values, write each solution or change your code to print i and j for each solution.
do a little analyze, you should easily be able to remove the inner loop.
with further analyze, you may be able to remove both loops and find a mathematical formula which will give you directly the answer.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900