What happend for this pow() function in while loop C++? - c++

I want to find sum of all digit in number power three
such as 14 = 1^3 + 4^3 = 65
I try to code in c++ like this below but it's wrong if I use pow() function.
int number;
int sum = 0;
std::cin >> number;
while(number > 0) {
sum += pow((number%10),3);
number /= 10;
}
std::cout << sum << std::endl;
return 0;
for code above.
if input 153
output should be = 3^3 + 5^3 + 1^3 = 153
but actual output is 152
but this code below it's work very well, Why ? Thank you
int number;
int sum = 0;
std::cin >> number;
while(number > 0) {
sum += (number % 10) * (number % 10) * (number % 10);
number /= 10;
}
std::cout << sum << std::endl;
return 0;

pow(,) is a function that's meant for floating point calculations, so what you get as the primary result is a float. When you assign this result to an int, it is implicitly converted (cast) to an integer, meaning it has to get rid of all the decimals.
So if the primary result happens to be 27.999999998 or something due to finite accuracy of the calculation, this will be converted to the integer 27. This is because float->int cast always rounds towards zero (it was defined that way, presumably due to efficiency reasons).

Function pow is for floating-point numbers and may loose precision when casted back to integer type. Try replacing it with round(pow(number%10,3)).

Related

My For Loop condition is not working even when the expression is

So I am trying to find the number of digits in a given int. The way I opted to find the digits was to divide the given int by powers of 10. Since I would be dividing by integers, the code would eventually reach a 0 when 10 is raised to a high enough power. There would be a tracker that tracks every iteration of this and that tracker would be able to tell me how digits there were.
#include <cmath>
#include <iostream>
int findDigits(int x)
{
//tracks the digits of int
int power{ 0 };
for (int i = 0; x / pow(10, i) != 0; i++) //the condition is not working as it should
{
//I checked the math expression and it is getting the intended result of zero at i = 3
int quotient = x / pow(10, i);
//I then checked the condition and it is becoming false when the expression results in 0
bool doesWork;
if (x / pow(10, i) != 0)
doesWork = true;
else
doesWork = false;
power = i;
}
return power;
}
int main()
{
std::cout << "157 has " << findDigits(157) << " digits";
return 0;
}
First, you are NOT dividing it by integer. pow() returns double according to the c++ reference. Therefore, the result of x / pow(10, i) would be double. ruining everything.
There is two option:
Use x / (int)pow(10, i) != 0 within the for loop condition. And PLUS 1 to the result.
But be aware, floating result of pow() might be corrupted.
If you don't have decent reason to use pow(), stick to the second option.
Go with below for loop instead.
for (; x != 0; x /= 10) {
power++;
}
It divides original number x by 10 until it reaches 0.

Can't get my code to divide with decimal precision

I'm trying to write a prime number indentify-er, but every time I try to divide the inputted number, it won't go to the decimals. I've tried using a double variable and float variable. I'm a beginner, so I might have to ask a few questions about your answer. Here is the code (looper is the number I used for the while function to keep it going).
#include <iostream>
int main() {
int input = 0;
float result = 0;
int looper = 2;
std::cout << "Please enter your number.\n";
std::cin >> input;
if (input == 1 or input == 0) {
std::cout << "Your number is neither.\n";
}
while (looper < 1000002) {
result = input / looper;
std::cout << input / looper;
if (fmod(result, 1) == 0) {
std::cout << "Your number is composite.\n";
std::cout << result;
looper = 1000003;
}
else if (fmod(result, 1) != 0) {
std::cout << "Your number is prime.\n";
}
looper = looper + 1;
}
}
There are some rules for arithmetic calculations.
if any of the operands is float or double, then the result is truncated to the float or double type respectively (int < float and int < double cause the size of int, float, double are 4, 8, 8 bytes respectively, but the sizes may be different depending on os & compiler.
if any of the operands is long type, then the result is truncated to the long type (int < long cause the size of int long types are 4, 8 bytes respectively, but the sizes may be different depending on os & compiler.)
However, you can do better alternative ( use moduler operator %) here like following:
if (input % looper == 0) {
// case for composit
// in other words input value is completely divisible by current value of looper
}
else {
// input value is not completely divisible by current value of looper
// this means there is a remainder exists
}
Though you have put the printf statement for prime number at wrong place, your provided algorithm is can be improved to determine whether an integer number is prime or not.

Non-restoring Floating Point Square Root Algorithm

I am trying to use the non-restoring algorithm for computing the square root of a floating point number.
For instance, say x = 1001, the square root is 31.6386
I want to calculate this square root using the non-restoring method.
I tried following the method in the paper:
Implementation of Single Precision Floating Point Square Root on FPGAs
but it appears my result is slightly off by 1 bit. I'm not able to figure out why though.
For instance, the program I wrote below will produce the following results:
correct_result =
41FD1BD2
myresult =
41FD1BD1
error =
1.192093e-007
C++ version of the code :
#include <iostream>
#include <cmath>
using namespace std;
union newfloat{
float f;
int i;
};
int main () {
// Input number
newfloat x;
cout << "Enter Number: ";
cin >> x.f;
// Pull out exponent and mantissa
int exponent = (x.i >> 23) & 0xFF;
int mantissa = (x.i & 0x7FFFFF) | ((exponent && exponent) << 23);
// Calculate new exponent
int new_exponent = (exponent >> 1) + 63 + (exponent & 1);
// Shift right (paper says shift left but shift left doesn't work?)
if (exponent & 1) {
mantissa = mantissa >> 1;
cout << " Shifted right " << endl;
}
// Create an array with the bits of the mantissa
unsigned int D [48];
for (int i = 47; i >= 0; i--) {
if (i >= 24) {
D[i] = (mantissa >> (i-24)) & 1;
} else {
D[i] = 0;
}
}
// == Perform square root ==
// Set q24 = 0, r24 = 0 and then iterate from k = 23 to 0
int q[25] = {0}; // 25 element array, indexing ends at 24
int r[25] = {0};
for (int k = 23; k >= 0; k--) {
if (r[k+1] >= 0) {
r[k] = ((r[k+1] << 2) | (D[2*k+1] << 1) | D[2*k] ) - (q[k+1] << 2 | 1 );
} else {
r[k] = ((r[k+1] << 2) | (D[2*k+1] << 1) | D[2*k] ) + (q[k+1] << 2 | 0x3 );
}
if (r[k] >= 0) {
q[k] = (q[k+1] << 1) | 1;
} else {
q[k] = q[k+1] << 1;
}
if (k == 0) {
if (r[0] < 0) {
r[0] = r[0] + (q[0] << 1) | 1;
}
}
}
// Create quotient from LSBs of q[]
int Q = 0;
for (int i = 0; i <= 23; i++) {
Q = Q | ((q[i] & 1) << i);
}
// Option 1 Rounding
//if (r[0] > 0) // Works for 10, 1001, 1021, but not 1012
// Q = Q + 1;
// Option 2 Rounding (No rounding)
// Works for 1012, Doesn't work for 10, 1001, 1021
// Option 3 Rounding (Calculate the next 3 Quotient bits to get a guard round and sticky bit)
// Calculate correct result:
newfloat correct_result;
correct_result.f = sqrt(x.f);
// Form my result into a single number
newfloat myresult;
myresult.i = (new_exponent << 23) | (Q & 0x7FFFFF);
// Print results
cout << hex << "My result: " << myresult.i << endl;
cout << hex << "Correct: " << correct_result.i << endl;
return 0;
}
First let me highlight the relevant part from the paper:
You need to take another look at how the additions/subtractions are done. You code is performing it in regular double-numbers, but I think the algorithm is designed with integer modular arithmetic in mind.
So if you look at the example listed later in the paper, the computation of 0011 - 0101 wraps around to give 1110.
That could explain why you're getting the wrong results, I think :)
I was looking through the c++ version of your program and reading that document today. It seems to me that the algorithm is intended to provide both a quotient and a remainder. As in the example provided, he uses his algorithm to get the square root of 127, to which it provides a result of 11 + R 6. 112 + 6 = 127.
That was with an integer, but every data type has a limit to its precision. This leads me to believe that your program is executing as expected, its just that you've run out of precision, at least for the way the square root is being calculated, and for the data type being used. I expect you would find your minute "lost" precision in r[0].
I saw from the comments in the code that you intended to, or tried to calculate out extra precision. That seems like a reasonable path to try. Do note that, in addition to the other changes that would be required to do this, you would have to take out (or move) the check k == 0; since it modifies the remainder, which would mess up the loop.
I think the real question is what size precision is acceptable to you. For instance, the c++ sqrt function (and yours) are off by 0.00000002 on sqrt(2). No one seems to mind. Considering the program you wrote is off from the c++ sqrt function by less than that in the instances where it doesn't match. I spent the majority of the day breaking it down, testing the individual parts, and reviewing the subject matter, and couldn't find anything blatantly wrong. It seem close enough for government work to me.

count the # of decimal digits after the radix point

I would like to count the number of decimal digits after the radix point of a floating point number.
The problem obviously raise when the real number doesn't have a representation in the binary system, like 3.5689113.
I am wondering - if for example someone write this real in a source code - if it is possible to get the number 7 namely the number of digits after the radix point
the naive following code for example doesn't work :
int main()
{
double num = 3.5689113;
int count = 0;
num = abs(num);
num = num - int(num);
while ( abs(num) >
0.0000001 )
{
num = num * 10;
count = count + 1;
num = num - int(num);
}
std::cout << count; //48
std::cin.ignore();
}
When something like that doesn't work, you try to print the numbers.
I did so here, and I found you had some floating number precision issues.
I changed the int rounding to ceil rounding and it worked like a charm.
Try putting the ints back and you'll see :)
EDIT: a better strategy than using ceils (which can give the same rounding problems) is to just round the numbers to the nearest integer. You can do that with floor(myNumber+0.5).
Here's the modified code
int main()
{
double num = 3.56891132326923333;
// Limit to 7 digits
num = floor(num*10000000 + 0.5)/10000000;
int count = 0;
num = abs(num);
num = num - floor(num+0.5);
while ( abs(num) >
0.0000001 )
{
cout << num << endl;
num = num * 10;
count = count + 1;
num = num - floor(num+0.5);
}
std::cout << count; //48
std::cin.ignore();
return 0;
}
To prevent the errors introduced by floating point approximation, convert the number to an integer at the earliest possible opportunity and work with that.
double num = 3.5689113;
int count = 7; // a maximum of 7 places
num = abs(num);
int remainder = int(0.5 + 10000000 * (num - int(num)));
while ( remainder % 10 == 0 )
{
remainder = remainder / 10;
--count;
}
For a floating point type T you can get up to std::numeric_limits<T>::digits10 digits restored exactly. Thus, to determine the position of the last non-zero fractional digits you'd use this value as a precision and format the number. To avoid the output using exponent notation you need to set the formatting flags to std::ios_base::fixed and account for the number of non-fractional digits:
std::ostringstream out;
int non_fraction(std::abs(value) < std::numeric_limits<double>::epsilon()
? 1: (1 + std::log(std::abs(value)) / std::log(10)));
out << std::setprecision(std::numeric_limits<double>::digits10 - non_fraction)
<< std::fixed
<< value;
If there is a decimal point, you just need to count the number of digits up to the trailing sequence of zeros.
I would recommend converting to a string, then looping over it and counting how many chars occur after you hit the period. Below is a sample (may need some minor tinkering, been awhile since I've done this in C++);
bool passedRadix = false
int i = 0; // for counting decimals
std::ostringstream strs;
strs << dbl; // dbl is 3.415 or whatever you're counting
std::string str = strs.str();
for(char& c : str) {
if (passedRadix == true)
i++;
if (c == '.')
passedRadix = true;
}

How can I seperate digits a given integer with C++?

Can you help me please? I try to do with while statement but I could not write the program.
Given an integer for example 12564897 and the program must show it 1-2-5-6-4-8-9-7
How do you detect in C++. Thanks a lot.
I tried with five digits integer.
int z,y,x,result,number1,number2,number3,number4,number5;
cout<<"Enter a five digit integer: ";
cin>>result; //read number
cout<<"The number is: "<<result<<endl;
number1 = result / 10000;
x = result / 1000;
number2 = x % 10;
y = result / 100;
number3 = y % 10;
z = result / 10;
number4 = z % 10;
number5 = result % 10;
cout<<"digits are: "<<number1<<"-"<<number2<<"-"<<number3<<"-"<<number4<<"-"<<number5<<endl;
system("pause");
return 0;
}
I think the smartest way is create a loop that divide by ten ( or the base ) and print the remainder, then divide by ten and do again. In preudo code:
let a = input
let base = 10
do
{
store a mod base in result
a = (integer) a / base;
}while(a>0)
print result reversed
mod is the remainder operator ( % in C/C++ )
please note thad by changing base you can have the digit in any representation of the number
Convert your Integer to a string and then print every character of that string with a - in between.
This is snippet from program which print out integer in reverse order.
You can modify it to fits your need (it's your homework)
//Read input number
cin >> dInput;
//Calculate log10
int logValue = (int)log10(dInput);
//Iteration through n-th power of 10
for(int i = logValue; i >= 0; i--) {
//Calculate actual power of 10
double d = pow(10,(double)i);
int n = (int)dInput / d;
//Subtract remainder from previous number
dInput -= (n * d);
//Print out "-"
cout << n;
if(i != 0) << "-";
}
I thought about writing the code itself, but since it's a homework, I'll give you the idea and let you code it
First, you'll convert that integer to a string using sprintf function
Then you'll make an integer having the size of the string. Let it be S
Then you'll make a for loop,
i=1, i < S, i+=2
i starts from 1 as the - is put after the first character
In that loop, you would insert the - character at the position of i, then you'll update integer S with the size. If you didn't update it, the following (for example) would happen
12345 (size = 5)
1-2345 (size = 5, real size = 6)
1-2-345 (size = 5, real size = 7)
It would stop here. As the condition i<5 would fail
That's all. Good luck.
OK, since everyone else has had a go, this is my attempt:
void outInt(int inInt){
int dividend;
dividend=inInt/10;
if (dividend!=0){
outInt(dividend);
cout<<"-"<<inInt%10;
}
else
cout<<(inInt);
};
No 'print result reversed' required. Should work for 0 and not print any '-' for numbers less than 10.