Having issues in power digit sum in C++ - c++

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
currently I am working on power digit sum in C++. my program is working properly but it gives inappropriate output.
#include<iostream>
#include<math.h>
using namespace std;
long double calculate(long double n)
{
long double i,j,temp = 0,sum = 0;
while(n != 0)
{
temp = fmod(n,10);
sum = sum + temp;
n = n / 10;
}
return sum;
}
int main()
{
long double i,j,n = 1000,temp = 1,value = 0;
for(i = 1;i <= n;i++)
{
temp = temp * 2;
}
cout << "Multiplication is : " << temp << endl;
value = calculate(temp);
cout.precision(100);
cout << "Sum is : " << value << endl;
return 0;
}
I am getting o/p like this.
Multiplication is : 1.07151e+301
Sum is : 1200.63580205668592182366438692042720504105091094970703125
it shouldn't be in points.it should print in digits.

Representing 2^1000 in binary would take a 1000 bits. Doubles are only 64bits long (long doubles are 80 or 128 bits depending on compiler/architecture). So doubles represent 2^1000 approximately. The input to calculate isn't 2^1000, but rather as close an approximation to it as 80bits allow. That approximation does not contain the lowest digits that calculate would like to sum over.

You can't use any primitive datatype to calculate 2^1000 and later sum of its digits, as its a big number (however, in languages like python and ruby you can do it).
For solving this problem in C/C++, you have to use array (or any other linear data structure like linked list, etc) and apply logic similar to usual pen-paper method of multiplying numbers.
First try to find a bound on number of digits in 2^1000 and then initialize an integer array of size greater than it with all zeroes. Keep the last element to be 1. Now multiply the array (thinking it as a large number such that each digit is in a different cell of the array) with 2, thousand times, taking modulo and carry overs.
Here is the code for above logic:
int ar[303];
int sum =0;
ar[0]=1;
for(int j=1;j<303;j++)
ar[j]=0;
for(int i=1;i<1001;i++)
{
ar[0]=2*ar[0];
for(int k=1;k<303;k++)
ar[k]=2*ar[k] + ar[k-1]/10;
for(int j=0;j<303;j++)
ar[j]=ar[j]%10;
}
for(int i=0;i<303;i++)
sum = sum + ar[i];
cout<<sum;
Hope it helps.

The reason why you are getting your sum with decimal points is because you are dividing a double by 10. This will not result in a clean integer unless the doubles last digit before the decimal point is a zero.
example:
376 / 10 = 37.6
370 / 10 = 37
To solve this change this in your code on line 12:
n = (n-temp)/10;
This will cut the float numbers from your sum at least.

finally i have solved my problem.
#include<iostream>
#include<math.h>
#include<string>
using namespace std;
long double calculate(string n)
{
long double i,j,temp = 0,sum = 0;
for (i = 0;i < n.length();i++)
{
if(n[i] == '.')
{
break;
}
sum = sum + (n[i] - 48);
}
return sum;
}
int main()
{
long double i,j,n = 1000,temp = 1,value = 0;
string str;
temp = pow(2,n);
cout << "Power is : " << temp << endl;
str = to_string(temp);
cout << str << endl;
value = calculate(str);
cout.precision(100);
cout << "Sum is : " << value << endl;
return 0;
}

Related

Wrong output- trying for if the number is Armstrong

I am new to coding and just starting with the c++ language, here I am trying to find the number given as input if it is Armstrong or not.
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153.
But even if I give not an armstrong number, it still prints that number is armstrong.
Below is my code.
#include <cmath>
#include <iostream>
using namespace std;
bool ifarmstrong(int n, int p) {
int sum = 0;
int num = n;
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
if(sum==n){
return true;
}else{
return false;
}
}
int main() {
int n;
cin >> n;
int i, p = 0;
for (i = 0; n > 0; i++) {
n = n / 10;
}
cout << i<<endl;
if (ifarmstrong(n, i)) {
cout << "Yes it is armstorng" << endl;
} else {
cout << "No it is not" << endl;
}
return 0;
}
A solution to my problem and explantation to what's wrong
This code
for (i = 0; n > 0; i++) {
n = n / 10;
}
will set n to zero after the loop has executed. But here
if (ifarmstrong(n, i)) {
you use n as if it still had the original value.
Additionally you have a error in your ifarmstrong function, this code
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
result in num being zero from the second iteration onwards. Presumably you meant to write this
while(num>0){
sum=sum+pow(num%10,p);
num=num/10;
}
Finally using pow on integers is unreliable. Because it's a floating point function and it (presumably) uses logarithms to do it's calculations, it may not return the exact integer result that you are expecting. It's better to use integers if you are doing exact integer calculations.
All these issues (and maybe more) will very quickly be discovered by using a debugger. much better than staring at code and scratching your head.

Kickstart 2022 interesting numbers

The question is to find the number of interesting numbers lying between two numbers. By the interesting number, they mean that the product of its digits is divisible by the sum of its digits.
For example: 459 => product = 4 * 5 * 9 = 180, and sum = 4 + 5 + 9 = 18; 180 % 18 == 0, hence it is an interesting number.
My solution for this problem is having run time error and time complexity of O(n2).
#include<iostream>
using namespace std;
int main(){
int x,y,p=1,s=0,count=0,r;
cout<<"enter two numbers"<<endl;
cin>>x>>y;
for(int i=x;i<=y;i++)
{
r=0;
while(i>1)
{
r=i%10;
s+=r;
p*=r;
i/=10;
}
if(p%s==0)
{
count++;
}
}
cout<<"count of interesting numbers are"<<count<<endl;
return 0;
}
If s is zero then if(p%s==0) will produce a divide by zero error.
Inside your for loop you modify the value of i to 0 or 1, this will mean the for loop never completes and will continuously check 1 and 2.
You also don't reinitialise p and s for each iteration of the for loop so will produce the wrong answer anyway. In general limit the scope of variables to where they are actually needed as this helps to avoid this type of bug.
Something like this should fix these problems:
#include <iostream>
int main()
{
std::cout << "enter two numbers\n";
int begin;
int end;
std::cin >> begin >> end;
int count = 0;
for (int number = begin; number <= end; number++) {
int sum = 0;
int product = 1;
int value = number;
while (value != 0) {
int digit = value % 10;
sum += digit;
product *= digit;
value /= 10;
}
if (sum != 0 && product % sum == 0) {
count++;
}
}
std::cout << "count of interesting numbers are " << count << "\n";
return 0;
}
I'd guess the contest is trying to get you to do something more efficient than this, for example after calculating the sum and product for 1234 to find the sum for 1235 you just need to add one and for the product you can divide by 4 then multiply by 5.

How do I convert a number into an 8-bit binary rather than 4-bit

void decimaltobin()
{
binaryNum = 0;
m = 1;
while (num != 0)
{
rem = num % 2;
num /= 2;
binaryNum += rem * m;
m *= 10;
}
}
Just wondering if there was an easy fix to get this function to print an 8-bit binary number instead of a 4-bit number, e.g. 0000 0101 instead of 0101.
As mentioned in the comments, your code does not print anything yet and the data type of binaryNum is not clear. Here is a working solution.
#include <iostream>
using namespace std;
void decToBinary(int n)
{
// array to store binary number
int binaryNum[32];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing the required number of zeros
int zeros = 8 - i;
for(int m = 0; m < zeros; m++){
cout<<0;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
// Driver program to test above function
int main()
{
int n = 17;
decToBinary(n);
return 0;
}
The code implements the following:
Store the remainder when the number is divided by 2 in an array.
Divide the number by 2
Repeat the above two steps until the number is greater than zero.
Print the required number of zeros. That is 8 - length of the binary number. Note that this code will work for numbers that can be expressed in 8 bits only.
Print the array in reverse order now
Ref
Maybe I am missing your reason but why do you want to code from scratch instead of using a standard library?
You may use standard c++ without having to code a conversion from scratch using for instance std::bitset<NB_OF_BITS>.
Here is a simple example:
#include <iostream>
#include <bitset>
std::bitset<8> decimalToBin(int numberToConvert)
{
return std::bitset<8>(numberToConvert);
}
int main() {
int a = 4, b=8, c=12;
std::cout << decimalToBin(a)<< std::endl;
std::cout << decimalToBin(b)<< std::endl;
std::cout << decimalToBin(c)<< std::endl;
}
It outputs:
00000100
00001000
00001100

Why a double is negative when it ought be positive?

I want to create an application that generates full list of phone numbers that satisfies equatation:
x is a rational number.
We can assume that
Now, after some transformations, we obtain
As telephone number is integer and 10^9 is integer, we know that t * 666333999 / s is integer. Therefore s is a divisor of t * 666333999
As yet, my programm searches for all divisors of 666333999. I thing it ought do it well (it should write most of the phone numbers). Unfortunately sometimes my phone number (it's the tym variable) is a negative number.
Why is it so?
Here's my code.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector < unsigned > divisor;
const int number = 666333999;
long double tym; // it's the phone number (9 digits)
for (int i = 2; i < number + 1; i++)
{ // I'm pushing all the divisors to vector.
if (number % i == 0)
{
divisor.push_back(i);
}
}
for(unsigned i = 1; i < divisor.size() + 1; i++)
{ // i are consecutives values of s
for(unsigned j = 1; j < (unsigned)2000000000; j++)
{ // j are consecutives values of t
tym = number / divisor[i];
tym *= j;
if(tym > 99999999 && tym < 2000000000) // I must substract 10^9
{
cout << "\t(!)\t i = " << i << " and j = " << j << ","
"div[i] = " << divisor[i] << ", telephone"
" number = " << (tym - 1000000000) << endl;
}
else if(tym >= 2000000000)
{
break;
}
}
}
}
The number involved in your calculation exceed the capability of a 32 bit integer but may fit the 64 bit integers.
May be in your platform int is 32 bit. Just use long long.
If you want to be sure about the 64 bit, use std::int64_t, defined in <cstdint>

Write number as sum of given integers

Here's the problem.
Write the given number N, as sum of the given numbers, using only additioning and subtracting.
Here's an example:
N = 20
Integers = 8, 15, 2, 9, 10
20 = 8 + 15 - 2 + 9 - 10.
Here's my idea;
First idea was to use brute force, alternating plus and minus. First I calculate the number of combinations and its 2^k (where k is the nubmer of integers), because I can alternate only minus and plus. Then I run through all numbers from 1 to 2^k and I convert it to binary form. And for any 1 I use plus and for any 0 I use minus. You'll get it easier with an example (using the above example).
The number of combinations is: 2^k = 2^5 = 32.
Now I run through all numbers from 1 to 32.
So i get: 1=00001, that means: -8-15-2-9+10 = -24 This is false so I go on.
2 = 00010, which means: -8-15-2+9-10 = -26. Also false.
This method works good, but when the number of integers is too big it takes too long.
Here's my code in C++:
#include <iostream>
#include <cmath>
using namespace std;
int convertToBinary(int number) {
int remainder;
int binNumber = 0;
int i = 1;
while(number!=0)
{
remainder=number%2;
binNumber=binNumber + (i*remainder);
number=number/2;
i=i*10;
}
return binNumber;
}
int main()
{
int N, numberOfIntegers, Combinations, Binary, Remainder, Sum;
cin >> N >> numberOfIntegers;
int Integers[numberOfIntegers];
for(int i = 0; i<numberOfIntegers; i++)
{
cin >>Integers[i];
}
Combinations = pow(2.00, numberOfIntegers);
for(int i = Combinations-1; i>=Combinations/2; i--) // I use half of the combinations, because 10100 will compute the same sum as 01011, but in with opposite sign.
{
Sum = 0;
Binary = convertToBinary(i);
for(int j = 0; Binary!=0; j++)
{
Remainder = Binary%10;
Binary = Binary/10;
if(Remainder==1)
{
Sum += Integers[numberOfIntegers-1-j];
}
else
{
Sum -= Integers[numberOfIntegers-1-j];
}
}
if(N == abs(Sum))
{
Binary = convertToBinary(i);
for(int j = 0; Binary!=0; j++)
{
Remainder = Binary%10;
Binary = Binary/10;
if(Sum>0)
{
if(Remainder==1)
{
cout << "+" << Integers[numberOfIntegers-1-j];
}
else
{
cout << "-" << Integers[numberOfIntegers-1-j];
}
}
else
{
if(Remainder==1)
{
cout << "-" << Integers[numberOfIntegers-1-j];
}
else
{
cout << "+" << Integers[numberOfIntegers-1-j];
}
}
}
break;
}
}
return 0;
}
Since this is typical homework, I'm not going to give the complete answer. But consider this:
K = +a[1] - a[2] - a[3] + a[4]
can be rewritten as
a[0] = K
a[0] + a[2] + a[3] = a[1] + a[4]
You now have normal subset sums on both sides.
So what you are worried about is you complexity .
Lets analyse what optimisations can be done.
Given n numbers in a[n] and target Value T;
And it is sure one combination of adding and subtracting gives you T ;
So Sigma(m*a[k]) =T where( m =(-1 or 1) and 0 >= k >= n-1 )
This just means ..
It can written as
(sum of Some numbers in array) = (Sum of remaining numbers in array) + T
Like in your case..
8+15-2+9-10=20 can be written as
8+15+9= 20+10+2
So Sum of all numbers including target = 64 // we can cal that .. :)
So half of it is 32 as
Which if further written as 20+(somthing)=32
which is 12 (2+10) in this case.
Your problem can be reduced to Finding the numbers in an array whose sum is 12 in this case
So your problem now can be reduced as find the combination of numbers whose sum is k (which you can calculate as described above k=12 .) For Which the complexity is O(log (n )) n as size of array , Keep in mind that you have to sort array and use binary search based algo for getting O(log(n)).
So as complexity can be made from O(2^n) to O((N+1)logN)as sorting included.
This takes static input as you have provided and i have written using core java
public static void main(String[] args) {
System.out.println("Enter number");
Scanner sc = new Scanner(System.in);
int total = 0;
while (sc.hasNext()) {
int[] array = new int[5] ;
for(int m=0;m<array.length;m++){
array[m] = sc.nextInt();
}
int res =array[0];
for(int i=0;i<array.length-1;i++){
if((array[i]%2)==1){
res = res - array[i+1];
}
else{
res =res+array[i+1];
}
}
System.out.println(res);
}
}