简体   繁体   English

C ++中10 ^ 9中的数字计算

[英]Calculation of digits in 10^9 in C++

I was trying to find the lcm of two numbers and for one of the input cases (28851539 and 1183019) my program returns a negative value . 我试图查找两个数字的lcm,对于一种输入情况(28851539和1183019),我的程序返回了负值。 Apparently it is not able to compute (28851529*1183019)/9 . 显然它无法计算(28851529 * 1183019)/ 9。

#include <iostream>
long long gcd(int a, int b) {
long long int temp;
if(a%b==0)
{
  return b;
}
else
{
 temp=a%b;
 return gcd(b,temp);
}
}
long long lcm(int a, int b , int g) {
//std::cout<<g;
long long int f=(a*b)/g;
return f;
}

int main() {
long long int a, b;
std::cin >> a >> b;
long long int g = gcd(a,b);
long long int q=lcm(a, b, g);
std::cout << q << std::endl;
return 0;
}

How do i compute that accurately ? 我该如何准确计算?

You problem is 你的问题是

long long int f=(a*b)/g;

since all of the types in (a*b)/g are int then this will be calculated as an int and if an int is 16 or 32 bits then it will overflow . 由于(a*b)/g中的所有类型均为int因此它将被计算为int ,如果int为16或32位,则它将溢出 Do note that since you have signed types this is actually undefined behavior . 请注意,由于您已签名类型,这实际上是未定义的行为 To get around this you either need to make a , b or g a long long int or you can change the parameters of the function to make them all long long int s. 为了解决这个问题,您需要将abglong long int或者可以更改函数的参数以使其全部为long long int s。

long long int lcm(long long int a, long long int b , long long int g)

I would also suggest you use an unsigned long long int if you are not dealing with negative numbers. 如果不处理负数,我还建议您使用unsigned long long int If you are not then you can use the type uint64_t from <cstdint> otherwise int64_t to make the type names shorter. 如果不是,则可以使用<cstdint> uint64_t类型,否则使用int64_t来缩短类型名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM