How to find the sum of elements on even position without usage of arrays etc, only normal operations?
For example:
159
Sum = 5.
159120
Sum = 5+1+0 = 6.
My work:
int sumofdigits(int x)
{
int sum = 0;
while(x > 0){
if (x % 100 != 0)
sum += x % 100;
x /= 100;
}
return sum;
}
Since you're counting "even" digits from the left, you first need to count the number of digits in order to know whether the least significant digit is even or not:
int sumOfEvenDigits(int x)
{
// First, count the number of digits
int digitCount = 0;
int tmp = x;
while(tmp) {
tmp /= 10;
digitCount++;
}
// If the number of digits is odd, throw away the least significant digit
if(digitCount % 2 == 1)
x /= 10;
// Keep adding the least significant digit, and throwing away two digits until you're done.
int sum = 0;
while(x){
sum += x % 10;
x /= 100;
}
return sum;
}
int accumulateIfEvenPos(int num, int pos) {
if (num == 0) return 0;
int digit = num % 10;
int next = num / 10;
return pos & 1 ? digit + accumulateIfOdd(next, ++pos) : accumulateIfOdd(next, ++pos);
}
You call it with pos 1 initially - demo here.
Well simple modification should do the trick.
int main()
{
int x = 1549;
//Get the number of digits
int length = snprintf(NULL, 0, "%i", x);
int sum = 0;
while(x > 0){
if (x % 100 != 0) {
//check if the number of digits is even to start from the last digit
if (length % 2 == 0) {
sum += x % 10;
x /= 10;
}
else {
x /= 10;
sum += x % 10;
}
x /= 10;
}
}
cout << sum << endl;
return 0;
}
EDIT: Solved the problem/bug in the algorithm. This might not be the best answer but I didn't want to completely write a different one(than the answer before edit).
You will need to have an index variable that keeps track of the position:
unsigned int digit_position = 0;
while (x > 0)
{
unsigned int digit_value = x % 10;
if (digit_position is even)
{
// Add digit_value to sum
}
// Shift value right one digit
x /= 10;
++digit_position;
}
There may be other methods using a position variable and the pow() function. But that is left as an exercise for the reader.
Related
In the following code I'm trying to find find the highest p (p is integer) number where 45^p is a divisor of n! (n is integer).
int n = 14;
long long unsigned int fact = 1;
for(int i = 1; i <= n; i++){
fact *= i;
}
bool until = true;
int ans;
// for goes until x is greater half of factorial
for(int i = 1; until; i++){
long long unsigned int x = 1;
for(int j = 1; j <= i; j++){
x *= 45;
}
if(fact/2 < x){
until = false;
}
else{
if(fact % x == 0){
ans = i;
}
}
}
cout << ans;
}
However, when I'm trying to end the loop at where x is greater than the half of factorial, it just keeps going on until 45^7 for some reason and it should stop at 45^5, where the number is lesser than half of n!. Why does this happen?
P.D: I'm not saying the program doesn't return the number I want (it returns ans = 2, which is true), but it's just pointless to keep on calculating x.
If you need the biggest value, starting from x = 45 and with x > fact / 2 the only way out of the loop, you have to get to at least the logarithm in base 45 of n! / 2.
And that's a limit of 7 because 45**6 <= 14! / 2 and 45**7 > 14! / 2.
Pen and pencil as suggested by #Raymond Chen is the way to go.
Strong number is the number that the sum of the factorial of its digits is equal to number itself.
For example: 145, since
1! + 4! + 5! = 1 + 24 + 120 = 145
Here is my code, It passes most of the test except one test
#include <string>
using namespace std;
string strong_num (int number )
{
int sum = 0;
while(number != 0) {
int last = number % 10;
number /= 10;
sum+= last * (last-1);
}
if(sum == number)
return "STRONG!!!!";
else
return "Not Strong !!";
}
What is wrong with my code?
I'm surprised you're passing any test cases at all. For one thing, you are destroying number before you compare it to sum, and for another your logic is flawed.
Try this:
int factorial (int x)
{
int result = 1;
while (x > 1)
{
result *= x;
x--;
}
return result;
}
string strong_num (int number)
{
int sum = 0;
int x = number;
while (x != 0) {
int digit = x % 10;
sum += factorial (digit);
x /= 10;
}
if (sum == number)
return "STRONG!!!!";
else
return "Not Strong !!";
}
Live demo
Replace int by long long to be able to test larger numbers.
There are two problems:
first - you are changing the value of number before comparing it to sum,
second - the thing you used last * (last-1) is not a definition of factorial, the definition of factorial is factorial(x) = 1 * 2 * 3 * ... * x
int factorial (int x) {
if(x < 2) return 1;
return x * factorial(x - 1);
}
string strong_num (int number)
{
int sum = 0;
int x = number;
while (x != 0) {
int last = x % 10;
sum += factorial (last);
x /= 10;
}
if (sum == number)
return "STRONG!!!!";
else
return "Not Strong !!";
}
class BigInt
{
private:
string data;
bool isNegative;
};
BigInt multiplication(BigInt left, BigInt right)
{
BigInt sum;
BigInt result;
sum.data.pop_back();
result.data.pop_back();
int count = 0;
int l1 = static_cast<int>(left.data.size());
int l2 = static_cast<int>(right.data.size());
int carry = 0;
for(int x = 0; x < l1 + l2; x++)
{
result.data.push_back('0');
}
for(int i = 0; i < l1; i++)
{
for(int k = count; k > 0 ; --k)
{
result.data.push_back('0');
}
for(int j = 0; j < l2; j++)
{
result = (left.data[j] - '0') * (right.data[i] - '0');
sum = sum + result;
if(result.data[i] >= 10)
{
carry = result.data[i + 1] / (10 - '0');
result.data[i] = (result.data[i] + '0') % 10;
}
else
{
carry = 0;
}
}
count++;
}
return sum;
}
I am suppose to be able to multiply very large numbers using strings. My code is working for single digits numbers only. Does anyone know why? Any insight would help greatly.
I can't multiply any numbers with more than one digit. I'm getting nothing for results.
This is a solution from geeksforgeeks which is very similar to what you are trying to do. I modified it to fit your class there might be an error as I have not compiled it.
BigInt multiplication(BigInt num1, BigInt num2)
{
int n1 = num1.data.size();
int n2 = num2.data.size();
if (n1 == 0 || n2 == 0)
return "0";
// will keep the result number in vector
// in reverse order
vector<int> result(n1 + n2, 0);
// Below two indexes are used to find positions
// in result.
int i_n1 = 0;
int i_n2 = 0;
// Go from right to left in num1
for (int i=n1-1; i>=0; i--)
{
int carry = 0;
int n1 = num1.data[i] - '0';
// To shift position to left after every
// multiplication of a digit in num2
i_n2 = 0;
// Go from right to left in num2
for (int j=n2-1; j>=0; j--)
{
// Take current digit of second number
int n2 = num2[j].data - '0';
// Multiply with current digit of first number
// and add result to previously stored result
// at current position.
int sum = n1*n2 + result[i_n1 + i_n2] + carry;
// Carry for next iteration
carry = sum/10;
// Store result
result[i_n1 + i_n2] = sum % 10;
i_n2++;
}
// store carry in next cell
if (carry > 0)
result[i_n1 + i_n2] += carry;
// To shift position to left after every
// multiplication of a digit in num1.
i_n1++;
}
// ignore '0's from the right
int i = result.size() - 1;
while (i>=0 && result[i] == 0)
i--;
// If all were '0's - means either both or
// one of num1 or num2 were '0'
if (i == -1)
return "0";
// generate the result string
string s = "";
while (i >= 0)
s += std::to_string(result[i--]);
BigInt temp(s, num1.isNegative ^ num2.isNegative);
return temp;
}
Hope this helps.
I've tried to check whether a number is a palindrome with the following code:
unsigned short digitsof (unsigned int x)
{
unsigned short n = 0;
while (x)
{
x /= 10;
n++;
}
return n;
}
bool ispalindrome (unsigned int x)
{
unsigned short digits = digitsof (x);
for (unsigned short i = 1; i <= digits / 2; i++)
{
if (x % (unsigned int)pow (10, i) != x % (unsigned int)pow (10, digits - 1 + i))
{
return false;
}
}
return true;
}
However, the following code isn't able to check for palindromes - false is always returned even if the number is a palindrome.
Can anyone point out the error?
(Please note: I'm not interested to make it into a string and reverse it to see where the problem is: rather, I'm interested to know where the error is in the above code.)
I personally would just build a string from the number, and then treat it as a normal palindrome check (check that each character in the first half matches the ones at length()-index).
x % (unsigned int)pow (10, i) is not the ith digit.
The problem is this:
x % (unsigned int)pow (10, i)
Lets try:
x =504405
i =3
SO I want 4.
x % 10^3 => 504405 %1000 => 405 NOT 4
How about
x / (unsigned int)pow (10, i -1) % 10
Just for more info! The following two functions are working for me:
double digitsof (double x)
{
double n = 0;
while (x > 1)
{
x /= 10;
n++;
}
return n;
}
bool ispalindrome (double x)
{
double digits = digitsof (x);
double temp = x;
for(double i = 1; i <= digits/2; i++)
{
float y = (int)temp % 10;
cout<<y<<endl;
temp = temp/10;
float z = (int)x / (int)pow(10 , digits - i);
cout<<(int)z<<endl;
x = (int)x % (int)pow(10 , digits - i);
if(y != z)
return false;
}
return true;
}
Code to check if given number is palindrome or not in JAVA
import java.util.*;
public class HelloWorld{
private static int countDigits(int num) {
int count = 0;
while(num>0) {
count++;
num /= 10;
}
return count;
}
public static boolean isPalin(int num) {
int digs = HelloWorld.countDigits(num);
int divderToFindMSD = 1;
int divderToFindLSD = 1;
for (int i = 0; i< digs -1; i++)
divderToFindMSD *= 10;
int mid = digs/2;
while(mid-- != 0)
{
int msd = (num/divderToFindMSD)%10;
int lsd = (num/divderToFindLSD)%10;
if(msd!=lsd)
return false;
divderToFindMSD /= 10;
divderToFindLSD *= 10;
}
return true;
}
public static void main(String []args) {
boolean isPalin = HelloWorld.isPalin(1221);
System.out.println("Results: " + isPalin);
}
}
I have done this with my own solution which is restricted with these conditions
Do not convert int to string.
Do not use any helper function.
var inputNumber = 10801
var firstDigit = 0
var lastDigit = 0
var quotient = inputNumber
while inputNumber > 0 {
lastDigit = inputNumber % 10
var tempNum = inputNumber
var count = 0
while tempNum > 0 {
tempNum = tempNum / 10
count = count + 1
}
var n = 1
for _ in 1 ..< count {
n = n * 10
}
firstDigit = quotient / n
if firstDigit != lastDigit {
print("Not a palindrome :( ")
break
}
quotient = quotient % n
inputNumber = inputNumber / 10
}
if firstDigit == lastDigit {
print("It's a palindrome :D :D ")
}
I've been trying to implement the algorithm from wikipedia and while it's never outputting composite numbers as primes, it's outputting like 75% of primes as composites.
Up to 1000 it gives me this output for primes:
3, 5, 7, 11, 13, 17, 41, 97, 193, 257, 641, 769
As far as I know, my implementation is EXACTLY the same as the pseudo-code algorithm. I've debugged it line by line and it produced all of the expected variable values (I was following along with my calculator). Here's my function:
bool primeTest(int n)
{
int s = 0;
int d = n - 1;
while (d % 2 == 0)
{
d /= 2;
s++;
}
// this is the LOOP from the pseudo-algorithm
for (int i = 0; i < 10; i++)
{
int range = n - 4;
int a = rand() % range + 2;
//int a = rand() % (n/2 - 2) + 2;
bool skip = false;
long x = long(pow(a, d)) % n;
if (x == 1 || x == n - 1)
continue;
for (int r = 1; r < s; r++)
{
x = long(pow(x, 2)) % n;
if (x == 1)
{
// is not prime
return false;
}
else if (x == n - 1)
{
skip = true;
break;
}
}
if (!skip)
{
// is not prime
return false;
}
}
// is prime
return true;
}
Any help would be appreciated D:
EDIT: Here's the entire program, edited as you guys suggested - and now the output is even more broken:
bool primeTest(int n);
int main()
{
int count = 1; // number of found primes, 2 being the first of course
int maxCount = 10001;
long n = 3;
long maxN = 1000;
long prime = 0;
while (count < maxCount && n <= maxN)
{
if (primeTest(n))
{
prime = n;
cout << prime << endl;
count++;
}
n += 2;
}
//cout << prime;
return 0;
}
bool primeTest(int n)
{
int s = 0;
int d = n - 1;
while (d % 2 == 0)
{
d /= 2;
s++;
}
for (int i = 0; i < 10; i++)
{
int range = n - 4;
int a = rand() % range + 2;
//int a = rand() % (n/2 - 2) + 2;
bool skip = false;
//long x = long(pow(a, d)) % n;
long x = a;
for (int z = 1; z < d; z++)
{
x *= x;
}
x = x % n;
if (x == 1 || x == n - 1)
continue;
for (int r = 1; r < s; r++)
{
//x = long(pow(x, 2)) % n;
x = (x * x) % n;
if (x == 1)
{
return false;
}
else if (x == n - 1)
{
skip = true;
break;
}
}
if (!skip)
{
return false;
}
}
return true;
}
Now the output of primes, from 3 to 1000 (as before), is:
3, 5, 17, 257
I see now that x gets too big and it just turns into a garbage value, but I wasn't seeing that until I removed the "% n" part.
The likely source of error is the two calls to the pow function. The intermediate results will be huge (especially for the first call) and will probably overflow, causing the error. You should look at the modular exponentiation topic at Wikipedia.
Source of problem is probably here:
x = long(pow(x, 2)) % n;
pow from C standard library works on floating point numbers, so using it is a very bad idea if you just want to compute powers modulo n. Solution is really simple, just square the number by hand:
x = (x * x) % n