Function return value (char and integer) - c++

I have a function that supposed to compute sum and return integer result, but it doesn't return the right value because when I multiply by 2 it takes value from ASCII table, not the integer value.
This part of the code is correct:
sum += *(ptrISBN + i) - '0'
, but when i try to multiply it by 2 it gives me ANSCII output, can someone help me to convert it into integer value somehow?
int checkSum(char *ptrISBN)
{
int sum = 0;
for (int i = 0; i < 14; i++) {
if (isdigit(*(ptrISBN + i)))
sum += *(ptrISBN + i) - '0' * 2;
}
return sum;
}

Try:
int checkSum(char *ptrISBN)
{
int sum = 0;
for (int i = 0; i < 14; i++) {
if (isdigit(*(ptrISBN + i)))
sum += (*(ptrISBN + i) - '0') * 2; //little change here
}
return sum;
}
I assume You wanted to convert character ('0' to '9') to its int value and then multiply it by 2.
Without change You were doing sum += *(ptrISBN + i) - ('0' * 2); which is not what You were looking for. That happened because multiplication was done before subtraction.

Related

Wrong output in Project Euler [duplicate]

I'm working on project euler problem number eight, in which ive been supplied this ridiculously large number:
7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
and am supposed to "Find the thirteen adjacent digits in the 1000-digit number that have the greatest product." EG the product of the first four adjacent digits is 7 * 3 * 1 * 6.
My code is the following:
int main()
{
string num = /* ridiculously large number omitted */;
int greatestProduct = 0;
int product;
for (int i=0; i < num.length() -12; i++)
{
product = ((int) num[i] - 48);
for (int j=i+1; j<i+13; j++)
{
product = product * ((int) num[j] - 48);
if (greatestProduct <= product)
{
greatestProduct = product;
}
}
}
cout << greatestProduct << endl;
}
I keep getting 2091059712 as the answer which project euler informs me is wrong and I suspect its too large anyway. Any help would be appreciated.
EDIT: changed to unsigned long int and it worked. Thanks everyone!
In fact your solution is too small rather than too big. The answer is what was pointed out in the comments, that there is integer overflow, and the clue is in the fact that your solution is close to the largest possible value for an signed int: 2147483647. You need to use a different type to store the product.
Note that the answer below is still 'correct' in that your code does do this wrong, but it's not what is causing the wrong value. Try taking your (working) code to http://codereview.stackexchange.com if you would like the folks there to tell you what you could improve in your approach and your coding style.
Previous answer
You are checking for a new greatest product inside the inner loop instead of outside. This means that your maximum includes all strings of less or equal ton 13 digits, rather than only exactly 13.
This could make a difference if you are finding a string which has fewer than 13 digits which have a large product, but a 0 at either end. You shouldn't count this as the largest, but your code does. (I haven't checked if this does actually happen.)
for (int i=0; i < num.length() -12; i++)
{
product = ((int) num[i] - 48);
for (int j=i+1; j<i+13; j++)
{
product = product * ((int) num[j] - 48);
}
if (greatestProduct <= product)
{
greatestProduct = product;
}
}
9^13 ≈ 2.54e12 (maximal possible value, needs 42 bit to be represented exactly), which doesn't fit into signed int. You should use int64.
If you don't want to mess with BigNum libraries, you could just take logarithms of your digits (rejecting 0) and add them up. It amounts to the same comparison.
A faster way without internal loop, but works only where there isn't a 0 in the input:
long long greatest(string num)
{
if (num.length() < 13)
return 0;
// Find a product of first 13 numbers.
long long product = 1;
unsigned int i;
for (i=0; i<13; ++i) {
product *= (num[i]-'0');
}
long long greatest_product = product;
// move through the large number
for (i=0; i+13<num.length(); ++i) {
product = product/(num[i]-'0')*(num[i+13]-'0');
if (greatest_product < product)
greatest_product = product;
}
return greatest_product;
}
In order to make this work with inputs containing 0, split the input string into substrings:
int main()
{
string num = /* input value*/;
long long greatest_product = 0;
size_t start = -1;
// Iterate over substrings without zero
do {
++start;
size_t end = num.find('0', start);
long long product = greatest(num.substr(start, end-start));
if (greatest_product < product)
greatest_product = product;
start = end;
} while (start != string::npos);
cout << greatest_product << endl;
}
My functional programming solution
def product(number):
product_result = 1
for n in number:
product_result *= int(n)
return product_result
length = 13
indices = range(0, len(number) - 13 + 1)
values = indices
values = map(lambda index: {"index": index, "number": number}, values)
values = map(lambda value: value["number"][value["index"]:value["index"] + length], values)
values = map(product, values)
values = max(values)
print values
public static void main(String[] args) {
String val = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
int Sum = 0;
String adjacent = null;
for (int i = 0; i < val.length()-13; i++) {
int total = 1;
for (int j = 0; j < 13; j++) {
total = total * Character.getNumericValue(val.charAt(i+j));
}
if(total > Sum){
Sum = total;
adjacent = val.substring(i, i+13);
}
}
System.out.println("Sum = " + Sum);
System.out.println("Adjsc = " + adjacent );
}
I had the same problem.
int product and int greatestproduct have maximum value it can store since they are 'int' type. They can only store values up to 2147483647.
Use 'long long' type instead of 'int'.
const thousandDigit =
`73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450`;
const productsOfAdjacentNths = num =>
[...thousandDigit].reduce((acc, _, idx) => {
const nthDigitAdjX = [...thousandDigit.substr(idx, num)].reduce(
(inAcc, inCur) => inCur * inAcc,
1
);
return acc.concat(nthDigitAdjX);
}, []);
console.log(Math.max(...productsOfAdjacentNths(13))); //5377010688
This is my O(n) approach
function findLargest(digits, n){
let largest = 0;
let j = 0;
let res = 1;
for(let i = 0; i< digits.length; i ++){
res = res * parseInt(digits[i]);
if(res == 0){
res = 1;
j = 0;
continue;
}
if(j === n-1){
if(res > largest)
largest = res;
res = res/parseInt(digits[i - j]);
j = j - 1;
}
j = j + 1;
}
return largest;
}
let val = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
findLargest(val, 13);
Although above solutions are good, here is a python implementation which works perfectly:
def main():
num=7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
prod,maxprod=1,0
numtostr=str(num)
length=len(numtostr)
for i in range(1,length-13+1):
prod=1
for z in range(i,i+13):
prod=prod*int(numtostr[z-1:z])
if prod>maxprod:
maxprod=prod
print "Largest 13 digit product is %d" %(maxprod)
if __name__ == '__main__':
main()
static long q8(){
long max_product = 1;
long product = 1;
String n = "LONG_INPUT";
for(int i=0;i<13;i++){
max_product *= Integer.parseInt(n.charAt(i)+"");
}
product = max_product;
for(int i=1;i<n.length()-13;i++){
int denom = Integer.parseInt(n.charAt(i-1)+"");
if(denom!=0)
product = product/denom * Integer.parseInt(n.charAt(i+12)+"");
else
product = product(i,n);
max_product = (max_product>product)?max_product:product;
}
return max_product;
}
static long product(int index,String n){
long pro = 1;
for(int i=index;i<index+13;i++){
pro *= Integer.parseInt(n.charAt(i)+"");
}
return pro;
}
Try this:
{
DateTime BeganAt = new DateTime();
BeganAt = DateTime.Now;
Int64 result = 0;
string testNumber = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
StringBuilder StringBuilder = new StringBuilder(13);
Int64 maxNumber = 0;
try
{
char[] numbers = testNumber.ToCharArray();
int tempCounter = 13;
for (int i = 0;i < numbers.Length;i++)
{
if(i < tempCounter)
{
StringBuilder.Append(numbers[i]);
}
else if (i == tempCounter)
{
if (maxNumber < Convert.ToInt64(StringBuilder.ToString()))
{
maxNumber = Convert.ToInt64(StringBuilder.ToString());
}
StringBuilder.Clear();
StringBuilder.Append(numbers[i]);
tempCounter = tempCounter + n;
}
}
result = maxNumber;
}
catch
{
throw;
}
DateTime EndedAt = new DateTime();
EndedAt = DateTime.Now;
TimeSpan TimeItTook = (EndedAt - BeganAt);
return Convert.ToString(result) + " - Time took to execute: " + Convert.ToString(TimeItTook.TotalMilliseconds);
}
long long int sum = 1,high=0;
for (int i = 0; i < 988; i++)
{
sum = sum*(arr[i] - 48);
for (int j = i + 1; j < i+13; j++)
{
sum = sum*(arr[j]-48);
}
if (sum >= high)
{
high = sum;
}
sum = 1;
}
My solution to above problem if someone is still watching this in 2018.Although there are lots of solution to this question here my solution pre-checks the individual 13 digits which have a 0 in them.As something multiplied with 0 is always 0 so we can remove this useless computation
int j = 0, k = 12;
long long int mult = 1;
long long int max = 0;
char *digits = /*Big number*/
while(k < 1000){
for (int i = j; i <= k; ++i)
{
/* code */
long long int val = digits[i] -'0';
/* check if any number in series contains 0 */
if(val == 0){
break;
}
mult = mult * val;
}
printf("mult is %lld\n",mult );
/* check for max value */
if(max < mult){
max = mult;
}
printf("the new max is %lld\n", max);
j += 1;
k += 1;
mult = 1;
printf("%d iteration finished\n", k);
}
printf("%lld\n", max);
You should use 'int64_t' at the place of 'int'
I have solve this problem using python 're' module
Finding all possible 13 digits number without having zeros (total 988 with zero and 283 without zero) then find the product of each of these digits and check for max
here i have used look ahead regex
Note: string must not contain any newline char
s = '731671765...'
import re
def product_13(d):
pro = 1
while d:
pro *= d % 10
d //= 10
return pro
pat = re.compile(r'(?=([1-9]{13}))')
all = map(int, re.findall(pat, s))
pro = -1
for i in all:
v = product_13(i)
if pro < v:
pro = v
print(pro)
**This is JavaScript solution.**
greatestProductOfAdjacentDigit = (givenNumber, noOfDigit) => {
stringNumberToNumbers = givenNumber => givenNumber.split('').map(each => parseInt(each, 10))
let numbers = mathematicalProblems.stringNumberToNumbers(givenNumber);
return numbers.map(function (each, ind, arr) {
return mathematicalProblems.productOfAll(arr.slice(ind, ind + noOfDigit));
}).reduce(function (accumulator, currentValue) {
return accumulator > currentValue ? accumulator : currentValue;
});
};
Testing
const givenNumber = '73167176531330624919225119674426574742355349' +
'194934969835203127745063262395783180169848018694788518438586' +
'156078911294949545950173795833195285320880551112540698747158' +
'523863050715693290963295227443043557668966489504452445231617' +
'318564030987111217223831136222989342338030813533627661428280' +
'644448664523874930358907296290491560440772390713810515859307' +
'960866701724271218839987979087922749219016997208880937766572' +
'733300105336788122023542180975125454059475224352584907711670' +
'556013604839586446706324415722155397536978179778461740649551' +
'492908625693219784686224828397224137565705605749026140797296' +
'865241453510047482166370484403199890008895243450658541227588' +
'666881164271714799244429282308634656748139191231628245861786' +
'645835912456652947654568284891288314260769004224219022671055' +
'626321111109370544217506941658960408071984038509624554443629' +
'812309878799272442849091888458015616609791913387549920052406' +
'368991256071760605886116467109405077541002256983155200055935' +
'72972571636269561882670428252483600823257530420752963450';
console.log(greatestProductOfAdjacentDigit(givenNumber, 4)); //5832
console.log(greatestProductOfAdjacentDigit(givenNumber, 13)); //23514624000
My 2 cents ... Javascript
Largest_product_in_series_13 = g => {
return [...g.matchAll(/(?=([1-9]{13}))/g)]
.reduce((a,c)=>(p=eval(c[1].split``.join`*`),p>a?p:a),0)
}
First it matches all 13 digit series, then it reduces to the biggest product.
console.log(Largest_product_in_series_13(`7316717653133062491922....
> 23514624000
start: 14.292ms
I solved it using ruby. if
x = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
then used below logic to solve the problem
def print_lps(x)
p = 1
0.upto(x.length-13) do |i|
j = i
xy = 1
while j < i+13 do
xy *= x[j].to_i
j += 1
end
p = xy if xy > p
end
puts p
end
print_lps(x) # 23514624000
I solve the problem using this approach
1.Run two loops first outer loop which iterate over numbers in the string.
2.Inner loop reach to next 13 numbers afterwards and store its product in a variable
3.As inner loop ends we only use maximum value.(that what we need) :>
Have a look at my code in C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s="//thestring is there";
long long unsigned mainans=1,ans=1; //initialize the value of mainans and ans to 1 (not 0 as product also become 0)
for(int i=0;i<s.length()-13;i++) //run the loop from 0 upto 13 minus string length
{
ans=1;
for(int j=i;j<i+13;j++) //now from that particular digit we check 13 digits afterwards it
{
int m=s[j]-'0'; //convert the number from string to integer
ans*=m; //taking product in every interation for 13 digits
}
mainans=max(mainans,ans); //now taking only max value because that what we need
}
cout<<mainans;
return 0;
}
This will find the answer in O(n) time and it handles zero. Written in Dart.
/**
* Main function
*
* Find the thirteen adjacent digits in the 1000-digit number that have the greatest product.
* What is the value of this product?
*
*/
const String DIGITS = "73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"12540698747158523863050715693290963295227443043557"
"66896648950445244523161731856403098711121722383113"
"62229893423380308135336276614282806444486645238749"
"30358907296290491560440772390713810515859307960866"
"70172427121883998797908792274921901699720888093776"
"65727333001053367881220235421809751254540594752243"
"52584907711670556013604839586446706324415722155397"
"53697817977846174064955149290862569321978468622482"
"83972241375657056057490261407972968652414535100474"
"82166370484403199890008895243450658541227588666881"
"16427171479924442928230863465674813919123162824586"
"17866458359124566529476545682848912883142607690042"
"24219022671055626321111109370544217506941658960408"
"07198403850962455444362981230987879927244284909188"
"84580156166097919133875499200524063689912560717606"
"05886116467109405077541002256983155200055935729725"
"71636269561882670428252483600823257530420752963450";
main(List<String> args) {
const int MAX_DIGITS = 13;
int len = DIGITS.length;
int digits = 0;
int largest = 0;
int current = 0;
int index = 0;
while (index < len) {
int value = int.parse(DIGITS[index]);
// if we get a zero then rebuild the MAX_DIGITS consecutive digits
if (value == 0) {
current = 0;
digits = 0;
} else {
// Multiply consecutive digits up to target set
if (digits < MAX_DIGITS) {
if (current == 0) {
current = value;
} else
current *= value;
digits++;
} else {
int divisor = int.parse(DIGITS[index - MAX_DIGITS]);
if (current == 0) {
current = value;
} else {
current = (current ~/ divisor);
current *= value;
}
}
if (current > largest) {
largest = current;
}
}
index++;
}
print('Num $largest');
}

Multiplying BigInts

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.

Codility MinAbsSum

I tried this Codility test: MinAbsSum.
https://codility.com/programmers/lessons/17-dynamic_programming/min_abs_sum/
I solved the problem by searching the whole tree of possibilities. The results were OK, however, my solution failed due to timeout for large input. In other words the time complexity was not as good as expected. My solution is O(nlogn), something normal with trees. But this coding test was in the section "Dynamic Programming", and there must be some way to improve it. I tried with summing the whole set first and then using this information, but always there is something missing in my solution. Does anybody have an idea on how to improve my solution using DP?
#include <vector>
using namespace std;
int sum(vector<int>& A, size_t i, int s)
{
if (i == A.size())
return s;
int tmpl = s + A[i];
int tmpr = s - A[i];
return min (abs(sum(A, i+1, tmpl)), abs(sum(A, i+1, tmpr)));
}
int solution(vector<int> &A) {
return sum(A, 0, 0);
}
I could not solve it. But here's the official answer.
Quoting it:
Notice that the range of numbers is quite small (maximum 100). Hence,
there must be a lot of duplicated numbers. Let count[i] denote the
number of occurrences of the value i. We can process all occurrences
of the same value at once. First we calculate values count[i] Then we
create array dp such that:
dp[j] = −1 if we cannot get the sum j,
dp[j] >= ­ 0 if we can get sum j.
Initially, dp[j] = -1 for all of j (except dp[0] = 0). Then we scan
through all the values a appearing in A; we consider all a such
that count[a]>0. For every such a we update dp that dp[j] denotes
how many values a remain (maximally) after achieving sum j. Note
that if the previous value at dp[j] >= 0 then we can set dp[j] =
count[a] as no value a is needed to obtain the sum j. Otherwise we
must obtain sum j-a first and then use a number a to get sum j. In
such a situation dp[j] = dp[j-a]-1. Using this algorithm, we can
mark all the sum values and choose the best one (closest to half of S,
the sum of abs of A).
def MinAbsSum(A):
N = len(A)
M = 0
for i in range(N):
A[i] = abs(A[i])
M = max(A[i], M)
S = sum(A)
count = [0] * (M + 1)
for i in range(N):
count[A[i]] += 1
dp = [-1] * (S + 1)
dp[0] = 0
for a in range(1, M + 1):
if count[a] > 0:
for j in range(S):
if dp[j] >= 0:
dp[j] = count[a]
elif (j >= a and dp[j - a] > 0):
dp[j] = dp[j - a] - 1
result = S
for i in range(S // 2 + 1):
if dp[i] >= 0:
result = min(result, S - 2 * i)
return result
(note that since the final iteration only considers sums up until S // 2 + 1, we can save some space and time by only creating a DP Cache up until that value as well)
The Java answer provided by fladam returns wrong result for input [2, 3, 2, 2, 3], although it gets 100% score.
Java Solution
import java.util.Arrays;
public class MinAbsSum{
static int[] dp;
public static void main(String args[]) {
int[] array = {1, 5, 2, -2};
System.out.println(findMinAbsSum(array));
}
public static int findMinAbsSum(int[] A) {
int arrayLength = A.length;
int M = 0;
for (int i = 0; i < arrayLength; i++) {
A[i] = Math.abs(A[i]);
M = Math.max(A[i], M);
}
int S = sum(A);
dp = new int[S + 1];
int[] count = new int[M + 1];
for (int i = 0; i < arrayLength; i++) {
count[A[i]] += 1;
}
Arrays.fill(dp, -1);
dp[0] = 0;
for (int i = 1; i < M + 1; i++) {
if (count[i] > 0) {
for(int j = 0; j < S; j++) {
if (dp[j] >= 0) {
dp[j] = count[i];
} else if (j >= i && dp[j - i] > 0) {
dp[j] = dp[j - i] - 1;
}
}
}
}
int result = S;
for (int i = 0; i < Math.floor(S / 2) + 1; i++) {
if (dp[i] >= 0) {
result = Math.min(result, S - 2 * i);
}
}
return result;
}
public static int sum(int[] array) {
int sum = 0;
for(int i : array) {
sum += i;
}
return sum;
}
}
I invented another solution, better than the previous one. I do not use recursion any more.
This solution works OK (all logical tests passed), and also passed some of the performance tests, but not all. How else can I improve it?
#include <vector>
#include <set>
using namespace std;
int solution(vector<int> &A) {
if (A.size() == 0) return 0;
set<int> sums, tmpSums;
sums.insert(abs(A[0]));
for (auto it = begin(A) + 1; it != end(A); ++it)
{
for (auto s : sums)
{
tmpSums.insert(abs(s + abs(*it)));
tmpSums.insert(abs(s - abs(*it)));
}
sums = tmpSums;
tmpSums.clear();
}
return *sums.begin();
}
This solution (in Java) scored 100% for both (correctness and performance)
public int solution(int[] a){
if (a.length == 0) return 0;
if (a.length == 1) return a[0];
int sum = 0;
for (int i=0;i<a.length;i++){
sum += Math.abs(a[i]);
}
int[] indices = new int[a.length];
indices[0] = 0;
int half = sum/2;
int localSum = Math.abs(a[0]);
int minLocalSum = Integer.MAX_VALUE;
int placeIndex = 1;
for (int i=1;i<a.length;i++){
if (localSum<half){
if (Math.abs(2*minLocalSum-sum) > Math.abs(2*localSum - sum))
minLocalSum = localSum;
localSum += Math.abs(a[i]);
indices[placeIndex++] = i;
}else{
if (localSum == half)
return Math.abs(2*half - sum);
if (Math.abs(2*minLocalSum-sum) > Math.abs(2*localSum - sum))
minLocalSum = localSum;
if (placeIndex > 1) {
localSum -= Math.abs(a[indices[placeIndex--]]);
i = indices[placeIndex];
}
}
}
return (Math.abs(2*minLocalSum - sum));
}
this solution treats all elements like they are positive numbers and it's looking to reach as close as it can to the sum of all elements divided by 2 (in that case we know that the sum of all other elements will be the same delta far from the half too -> abs sum will be minimum possible ).
it does so by starting with the first element and successively adding others to the "local" sum (and recording indices of elements in the sum) until it reaches sum of x >= sumAll/2. if that x is equal to sumAll/2 we have an optimal solution. if not, we go step back in the indices array and continue picking other element where last iteration in that position ended. the result will be a "local" sum having abs((sumAll - sum) - sum) closest to 0;
fixed solution:
public static int solution(int[] a){
if (a.length == 0) return 0;
if (a.length == 1) return a[0];
int sum = 0;
for (int i=0;i<a.length;i++) {
a[i] = Math.abs(a[i]);
sum += a[i];
}
Arrays.sort(a);
int[] arr = a;
int[] arrRev = new int[arr.length];
int minRes = Integer.MAX_VALUE;
for (int t=0;t<=4;t++) {
arr = fold(arr);
int res1 = findSum(arr, sum);
if (res1 < minRes) minRes = res1;
rev(arr, arrRev);
int res2 = findSum(arrRev, sum);
if (res2 < minRes) minRes = res2;
arrRev = fold(arrRev);
int res3 = findSum(arrRev, sum);
if (res3 < minRes) minRes = res3;
}
return minRes;
}
private static void rev(int[] arr, int[] arrRev){
for (int i = 0; i < arrRev.length; i++) {
arrRev[i] = arr[arr.length - 1 - i];
}
}
private static int[] fold(int[] a){
int[] arr = new int[a.length];
for (int i=0;a.length/2+i/2 < a.length && a.length/2-i/2-1 >= 0;i+=2){
arr[i] = a[a.length/2+i/2];
arr[i+1] = a[a.length/2-i/2-1];
}
if (a.length % 2 > 0) arr[a.length-1] = a[a.length-1];
else{
arr[a.length-2] = a[0];
arr[a.length-1] = a[a.length-1];
}
return arr;
}
private static int findSum(int[] arr, int sum){
int[] indices = new int[arr.length];
indices[0] = 0;
double half = Double.valueOf(sum)/2;
int localSum = Math.abs(arr[0]);
int minLocalSum = Integer.MAX_VALUE;
int placeIndex = 1;
for (int i=1;i<arr.length;i++){
if (localSum == half)
return 2*localSum - sum;
if (Math.abs(2*minLocalSum-sum) > Math.abs(2*localSum - sum))
minLocalSum = localSum;
if (localSum<half){
localSum += Math.abs(arr[i]);
indices[placeIndex++] = i;
}else{
if (placeIndex > 1) {
localSum -= Math.abs(arr[indices[--placeIndex]]);
i = indices[placeIndex];
}
}
}
return Math.abs(2*minLocalSum - sum);
}
The following is a rendering of the official answer in C++ (scoring 100% in task, correctness, and performance):
#include <cmath>
#include <algorithm>
#include <numeric>
using namespace std;
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
const int N = A.size();
int M = 0;
for (int i=0; i<N; i++) {
A[i] = abs(A[i]);
M = max(M, A[i]);
}
int S = accumulate(A.begin(), A.end(), 0);
vector<int> counts(M+1, 0);
for (int i=0; i<N; i++) {
counts[A[i]]++;
}
vector<int> dp(S+1, -1);
dp[0] = 0;
for (int a=1; a<M+1; a++) {
if (counts[a] > 0) {
for (int j=0; j<S; j++) {
if (dp[j] >= 0) {
dp[j] = counts[a];
} else if ((j >= a) && (dp[j-a] > 0)) {
dp[j] = dp[j-a]-1;
}
}
}
}
int result = S;
for (int i =0; i<(S/2+1); i++) {
if (dp[i] >= 0) {
result = min(result, S-2*i);
}
}
return result;
}
You are almost 90% to the actual solution. It seems you understand recursion very well. Now, You should apply dynamic programming here with your program.
Dynamic Programming is nothing but memoization to the recursion so that we will not calculate same sub problems again and again. If same sub problems encounter , we return the previously calculated and memorized value. Memorization can be done with the help of a 2D array , say dp[][], where first state represent current index of array and second state represent summation.
For this problem specific, instead of giving calls to both states from each state, you sometimes can greedily take decision to skip one call.
I would like to provide the algorithm and then my implementation in C++. Idea is more or less the same as the official codility solution with some constant optimisation added.
Calculate the maximum absolute element of the inputs.
Calculate the absolute sum of the inputs.
Count the number of occurrence of each number in the inputs. Store the results in a vector hash.
Go through each input.
For each input, goes through all possible sums of any number of inputs. It is a slight constant optimisation to go only up to half of the possible sums.
For each sum that has been made before, set the occurrence count of the current input.
Check for each potential sum equal to or greater than the current input whether this input has already been used before. Update the values at the current sum accordingly. We do not need to check for potential sums less than the current input in this iteration, since it is evident that it has not been used before.
The above nested loop will fill in each possible sum with a value greater than -1.
Go through this possible sum hash again to look for the closest sum to half that is possible to make. Eventually, the min abs sum will be the difference of this from the half multiplied by two as the difference will be added up in both groups as the difference from the median.
The runtime complexity of this algorithm is O(N * max(abs(A)) ^ 2), or simply O(N * M ^ 2). That is because the outer loop is iterating M times and the inner loop is iterating sum times. The sum is basically N * M in worst case. Therefore, it is O(M * N * M).
The space complexity of this solution is O(N * M) because we allocate a hash of N items for the counts and a hash of S items for the sums. S is N * M again.
int solution(vector<int> &A)
{
int M = 0, S = 0;
for (const int e : A) { M = max(abs(e), M); S += abs(e); }
vector<int> counts(M + 1, 0);
for (const int e : A) { ++counts[abs(e)]; }
vector<int> sums(S + 1, -1);
sums[0] = 0;
for (int ci = 1; ci < counts.size(); ++ci) {
if (!counts[ci]) continue;
for (int si = 0; si < S / 2 + 1; ++si) {
if (sums[si] >= 0) sums[si] = counts[ci];
else if (si >= ci and sums[si - ci] > 0) sums[si] = sums[si - ci] - 1;
}
}
int min_abs_sum = S;
for (int i = S / 2; i >= 0; --i) if (sums[i] >= 0) return S - 2 * i;
return min_abs_sum;
}
Let me add my 50 cent, how to come up with the score 100% solution.
For me it was hard to understand the ultimate solution, proposed earlier in this thread.
So I started with warm-up solution with score 63%, because its O(NxNxM),
and because it doesn't use the fact that M is quite small value, and there are many duplicates in big arrays
here the key part is to understand how array isSumPossible is filled and interpreted:
how to fill array isSumPossible using numbers in input array:
if isSumPossible[sum] >= 0, i.e. sum is already possible, even without current number, then let's set it's value to 1 - count of current number, that is left unused for this sum, it'll go to our "reserve", so we can use it later for greater sums.
if (isSumPossible[sum] >= 0) {
isSumPossible[sum] = 1;
}
if isSumPossible[sum] <= 0, i.e. sum is considered not yet possible, with all input numbers considered previously, then let's check maybe
smaller sum sum - number is already considered as possible, and we have in "reserve" our current number (isSumPossible[sum - number] == 1), then do following
else if (sum >= number && isSumPossible[sum - number] == 1) {
isSumPossible[sum] = 0;
}
here isSumPossible[sum] = 0 means that we have used number in composing sum and it's now considered as possible (>=0), but we have no number in "reserve", because we've used it ( =0)
how to interpret filled array isSumPossible after considering all numbers in input array:
if isSumPossible[sum] >= 0 then the sum is possible, i.e. it can be reached by summation of some numbers in given array
if isSumPossible[sum] < 0 then the sum can't be reached by summation of any numbers in given array
The more simple thing here is to understand why we are searching sums only in interval [0, maxSum/2]:
because if find a possible sum, that is very close to maxSum/2,
ideal case here if we've found possible sum = maxSum/2,
if so, then it's obvious, that we can somehow use the rest numbers in input array to make another maxSum/2, but now with negative sign, so as a result of annihilation we'll get solution = 0, because maxSum/2 + (-1)maxSum/2 = 0.
But 0 the best case solution, not always reachable.
But we, nevertheless, should seek for the minimal delta = ((maxSum - sum) - sum),
so this we seek for delta -> 0, that's why we have this:
int result = Integer.MAX_VALUE;
for (int sum = 0; sum < maxSum / 2 + 1; sum++) {
if (isSumPossible[sum] >= 0) {
result = Math.min(result, (maxSum - sum) - sum);
}
}
warm-up solution
public int solution(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
if (A.length == 1) {
return A[0];
}
int maxSum = 0;
for (int i = 0; i < A.length; i++) {
A[i] = Math.abs(A[i]);
maxSum += A[i];
}
int[] isSumPossible = new int[maxSum + 1];
Arrays.fill(isSumPossible, -1);
isSumPossible[0] = 0;
for (int number : A) {
for (int sum = 0; sum < maxSum / 2 + 1; sum++) {
if (isSumPossible[sum] >= 0) {
isSumPossible[sum] = 1;
} else if (sum >= number && isSumPossible[sum - number] == 1) {
isSumPossible[sum] = 0;
}
}
}
int result = Integer.MAX_VALUE;
for (int sum = 0; sum < maxSum / 2 + 1; sum++) {
if (isSumPossible[sum] >= 0) {
result = Math.min(result, maxSum - 2 * sum);
}
}
return result;
}
and after this we can optimize it, using the fact that there are many duplicate numbers in big arrays, and we come up with the solution with 100% score, its O(Mx(NxM)), because maxSum = NxM at worst case
public int solution(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
if (A.length == 1) {
return A[0];
}
int maxNumber = 0;
int maxSum = 0;
for (int i = 0; i < A.length; i++) {
A[i] = Math.abs(A[i]);
maxNumber = Math.max(maxNumber, A[i]);
maxSum += A[i];
}
int[] count = new int[maxNumber + 1];
for (int i = 0; i < A.length; i++) {
count[A[i]]++;
}
int[] isSumPossible = new int[maxSum + 1];
Arrays.fill(isSumPossible, -1);
isSumPossible[0] = 0;
for (int number = 0; number < maxNumber + 1; number++) {
if (count[number] > 0) {
for (int sum = 0; sum < maxSum / 2 + 1; sum++) {
if (isSumPossible[sum] >= 0) {
isSumPossible[sum] = count[number];
} else if (sum >= number && isSumPossible[sum - number] > 0) {
isSumPossible[sum] = isSumPossible[sum - number] - 1;
}
}
}
}
int result = Integer.MAX_VALUE;
for (int sum = 0; sum < maxSum / 2 + 1; sum++) {
if (isSumPossible[sum] >= 0) {
result = Math.min(result, maxSum - 2 * sum);
}
}
return result;
}
I hope I've made it at least a little clear
Kotlin solution
Time complexity: O(N * max(abs(A))**2)
Score: 100%
import kotlin.math.*
fun solution(A: IntArray): Int {
val N = A.size
var M = 0
for (i in 0 until N) {
A[i] = abs(A[i])
M = max(M, A[i])
}
val S = A.sum()
val counts = MutableList(M + 1) { 0 }
for (i in 0 until N) {
counts[A[i]]++
}
val dp = MutableList(S + 1) { -1 }
dp[0] = 0
for (a in 1 until M + 1) {
if (counts[a] > 0) {
for (j in 0 until S) {
if (dp[j] >= 0) {
dp[j] = counts[a]
} else if (j >= a && dp[j - a] > 0) {
dp[j] = dp[j - a] - 1
}
}
}
}
var result = S
for (i in 0 until (S / 2 + 1)) {
if (dp[i] >= 0) {
result = minOf(result, S - 2 * i)
}
}
return result
}

Addition of every subset of two multiplied

I have an array with the elements {7,2,1} and the idea is to do 7 * 2 + 7 * 1 + 2 * 1 which is basically this algorithm:
for(int i=0;i<n-1;++i)
for(int k=i+1;k<n;++k)
sum += a[i] * a[k];
Where a is the array in which I have the numbers and n is the number of elements, I need a more efficient algorithm for doing this, and I have no clue how to do it, can someone give me a hand?
Thank you!
You can do better in the general case. Time to do some math. Let's look at the 3-element version, we have:
ab + ac + bc
= 1/2 * (2ab + 2ac + 2bc)
= 1/2 * (2ab + 2ac + 2bc + a^2 + b^2 + c^2 - (a^2 + b^2 + c^2))
= 1/2 * ((a+b+c)^2 - (a^2 + b^2 + c^2))
That is:
int sum = 0;
int sum_sq = 0;
for (int i : arr) {
sum += i;
sum_sq += i*i;
}
int result = (sum*sum - sum_sq) / 2;
This is O(n) multiplications, instead of O(n^2). This'll certainly be better than the naive implementation at some point. Whether or not it's better for just 3 elements is something I haven't timed.
#chux's suggestion is essentially to redistribute operations:
ai * ai + 1 + ai * ai + 2 + ... + ai * an
-->
ai * (ai + 1 + ... + an)
combined with the avoiding unnecessary recomputation of partial sums of the (ai + 1 + ... + an) terms by leveraging the fact that each differs from the next by the value of one element of the input array.
Here's a one-pass implementation with O(1) overhead:
int psum(size_t n, int array[n]) {
int result = 0;
int rsum = array[n - 1];
for (int i = n - 2; i >= 0; i--) {
result += array[i] * rsum;
rsum += array[i];
}
return result;
}
The sum of all elements to the right of index i is maintained from iteration to iteration in variable rsum. It's unnecessary to track its various values in an array, because we need each value only for one iteration of the loop.
This scales linearly with the number of elements in the input array. You'll see that the number and type of operations is quite similar to #Barry's answer, but nothing analogous to his final step is required, which saves a few operations.
As #Barry observes in comments, the iteration can also be run in the other direction, in conjunction with tracking the left-hand partial sums intead of the right-hand ones. That would diverge a bit more from #chux's description, but it relies on exactly the same principles.
We have (a + b + c + ...)2 = (a2 + b2 + c2 + ...) + 2(ab + bc + ca + ...)
You want the sum S = ab + bc + ca + ..., which has O(n2) pairs (using 2 nested loops)
You can do 2 separated loops, one calculates P = a2 + b2 + c2 + ... in O(n) time, and another calculates Q = (a + b + c + ...)2 also in O(n) time. Then take S = (Q - P) / 2.
Make 1 pass, walk from the end of [a] to the front and form a sum of all the elements "to the right".
2nd pass, Multiple a[i] * sum[i].
O(n).
long sum0(int a[], int n) {
long sum = 0;
for (int i = 0; i < n - 1; ++i)
for (int k = i + 1; k < n; ++k)
sum += a[i] * a[k];
return sum;
}
long sum1(int a[], int n) {
int long sums[n];
sums[n - 1] = 0;
for (int i = n - 2; i >= 0; i--) {
sums[i] = a[i+1] + sums[i + 1];
}
long sum = 0;
for (int i = 0; i < n - 1; ++i)
sum += a[i] * sums[i];
return sum;
}
void test(int a[], int n) {
long s0 = sum0(a, n);
long s1 = sum1(a, n);
if (s0 != s1) printf("%9ld %9ld\n", s0, s1);
}
void tests(int k) {
while (k--) {
int n = rand() % 10 + 2;
int a[n + 1];
for (int m = 0; m < n; m++)
a[m] = rand() % 256;
test(a, n);
}
}
int main() {
int a[3] = { 7, 2, 1 };
printf("%d\n", sum1(a, 3));
tests(1000000);
puts("Done");
}
As it turns out the sums[] array is not needed either as the the running sums needs only 1 location. This effectively makes this answers similar to others
long sum1(int a[], int n) {
int long sums = 0;
long sum = 0;
for (int i = n - 2; i >= 0; i--) {
sums = a[i+1] + sums;
sum += a[i] * sums;
}
return sum;
}

Project Euler #8, I don't understand where I'm going wrong

I'm working on project euler problem number eight, in which ive been supplied this ridiculously large number:
7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
and am supposed to "Find the thirteen adjacent digits in the 1000-digit number that have the greatest product." EG the product of the first four adjacent digits is 7 * 3 * 1 * 6.
My code is the following:
int main()
{
string num = /* ridiculously large number omitted */;
int greatestProduct = 0;
int product;
for (int i=0; i < num.length() -12; i++)
{
product = ((int) num[i] - 48);
for (int j=i+1; j<i+13; j++)
{
product = product * ((int) num[j] - 48);
if (greatestProduct <= product)
{
greatestProduct = product;
}
}
}
cout << greatestProduct << endl;
}
I keep getting 2091059712 as the answer which project euler informs me is wrong and I suspect its too large anyway. Any help would be appreciated.
EDIT: changed to unsigned long int and it worked. Thanks everyone!
In fact your solution is too small rather than too big. The answer is what was pointed out in the comments, that there is integer overflow, and the clue is in the fact that your solution is close to the largest possible value for an signed int: 2147483647. You need to use a different type to store the product.
Note that the answer below is still 'correct' in that your code does do this wrong, but it's not what is causing the wrong value. Try taking your (working) code to http://codereview.stackexchange.com if you would like the folks there to tell you what you could improve in your approach and your coding style.
Previous answer
You are checking for a new greatest product inside the inner loop instead of outside. This means that your maximum includes all strings of less or equal ton 13 digits, rather than only exactly 13.
This could make a difference if you are finding a string which has fewer than 13 digits which have a large product, but a 0 at either end. You shouldn't count this as the largest, but your code does. (I haven't checked if this does actually happen.)
for (int i=0; i < num.length() -12; i++)
{
product = ((int) num[i] - 48);
for (int j=i+1; j<i+13; j++)
{
product = product * ((int) num[j] - 48);
}
if (greatestProduct <= product)
{
greatestProduct = product;
}
}
9^13 ≈ 2.54e12 (maximal possible value, needs 42 bit to be represented exactly), which doesn't fit into signed int. You should use int64.
If you don't want to mess with BigNum libraries, you could just take logarithms of your digits (rejecting 0) and add them up. It amounts to the same comparison.
A faster way without internal loop, but works only where there isn't a 0 in the input:
long long greatest(string num)
{
if (num.length() < 13)
return 0;
// Find a product of first 13 numbers.
long long product = 1;
unsigned int i;
for (i=0; i<13; ++i) {
product *= (num[i]-'0');
}
long long greatest_product = product;
// move through the large number
for (i=0; i+13<num.length(); ++i) {
product = product/(num[i]-'0')*(num[i+13]-'0');
if (greatest_product < product)
greatest_product = product;
}
return greatest_product;
}
In order to make this work with inputs containing 0, split the input string into substrings:
int main()
{
string num = /* input value*/;
long long greatest_product = 0;
size_t start = -1;
// Iterate over substrings without zero
do {
++start;
size_t end = num.find('0', start);
long long product = greatest(num.substr(start, end-start));
if (greatest_product < product)
greatest_product = product;
start = end;
} while (start != string::npos);
cout << greatest_product << endl;
}
My functional programming solution
def product(number):
product_result = 1
for n in number:
product_result *= int(n)
return product_result
length = 13
indices = range(0, len(number) - 13 + 1)
values = indices
values = map(lambda index: {"index": index, "number": number}, values)
values = map(lambda value: value["number"][value["index"]:value["index"] + length], values)
values = map(product, values)
values = max(values)
print values
public static void main(String[] args) {
String val = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
int Sum = 0;
String adjacent = null;
for (int i = 0; i < val.length()-13; i++) {
int total = 1;
for (int j = 0; j < 13; j++) {
total = total * Character.getNumericValue(val.charAt(i+j));
}
if(total > Sum){
Sum = total;
adjacent = val.substring(i, i+13);
}
}
System.out.println("Sum = " + Sum);
System.out.println("Adjsc = " + adjacent );
}
I had the same problem.
int product and int greatestproduct have maximum value it can store since they are 'int' type. They can only store values up to 2147483647.
Use 'long long' type instead of 'int'.
const thousandDigit =
`73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450`;
const productsOfAdjacentNths = num =>
[...thousandDigit].reduce((acc, _, idx) => {
const nthDigitAdjX = [...thousandDigit.substr(idx, num)].reduce(
(inAcc, inCur) => inCur * inAcc,
1
);
return acc.concat(nthDigitAdjX);
}, []);
console.log(Math.max(...productsOfAdjacentNths(13))); //5377010688
This is my O(n) approach
function findLargest(digits, n){
let largest = 0;
let j = 0;
let res = 1;
for(let i = 0; i< digits.length; i ++){
res = res * parseInt(digits[i]);
if(res == 0){
res = 1;
j = 0;
continue;
}
if(j === n-1){
if(res > largest)
largest = res;
res = res/parseInt(digits[i - j]);
j = j - 1;
}
j = j + 1;
}
return largest;
}
let val = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
findLargest(val, 13);
Although above solutions are good, here is a python implementation which works perfectly:
def main():
num=7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
prod,maxprod=1,0
numtostr=str(num)
length=len(numtostr)
for i in range(1,length-13+1):
prod=1
for z in range(i,i+13):
prod=prod*int(numtostr[z-1:z])
if prod>maxprod:
maxprod=prod
print "Largest 13 digit product is %d" %(maxprod)
if __name__ == '__main__':
main()
static long q8(){
long max_product = 1;
long product = 1;
String n = "LONG_INPUT";
for(int i=0;i<13;i++){
max_product *= Integer.parseInt(n.charAt(i)+"");
}
product = max_product;
for(int i=1;i<n.length()-13;i++){
int denom = Integer.parseInt(n.charAt(i-1)+"");
if(denom!=0)
product = product/denom * Integer.parseInt(n.charAt(i+12)+"");
else
product = product(i,n);
max_product = (max_product>product)?max_product:product;
}
return max_product;
}
static long product(int index,String n){
long pro = 1;
for(int i=index;i<index+13;i++){
pro *= Integer.parseInt(n.charAt(i)+"");
}
return pro;
}
Try this:
{
DateTime BeganAt = new DateTime();
BeganAt = DateTime.Now;
Int64 result = 0;
string testNumber = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
StringBuilder StringBuilder = new StringBuilder(13);
Int64 maxNumber = 0;
try
{
char[] numbers = testNumber.ToCharArray();
int tempCounter = 13;
for (int i = 0;i < numbers.Length;i++)
{
if(i < tempCounter)
{
StringBuilder.Append(numbers[i]);
}
else if (i == tempCounter)
{
if (maxNumber < Convert.ToInt64(StringBuilder.ToString()))
{
maxNumber = Convert.ToInt64(StringBuilder.ToString());
}
StringBuilder.Clear();
StringBuilder.Append(numbers[i]);
tempCounter = tempCounter + n;
}
}
result = maxNumber;
}
catch
{
throw;
}
DateTime EndedAt = new DateTime();
EndedAt = DateTime.Now;
TimeSpan TimeItTook = (EndedAt - BeganAt);
return Convert.ToString(result) + " - Time took to execute: " + Convert.ToString(TimeItTook.TotalMilliseconds);
}
long long int sum = 1,high=0;
for (int i = 0; i < 988; i++)
{
sum = sum*(arr[i] - 48);
for (int j = i + 1; j < i+13; j++)
{
sum = sum*(arr[j]-48);
}
if (sum >= high)
{
high = sum;
}
sum = 1;
}
My solution to above problem if someone is still watching this in 2018.Although there are lots of solution to this question here my solution pre-checks the individual 13 digits which have a 0 in them.As something multiplied with 0 is always 0 so we can remove this useless computation
int j = 0, k = 12;
long long int mult = 1;
long long int max = 0;
char *digits = /*Big number*/
while(k < 1000){
for (int i = j; i <= k; ++i)
{
/* code */
long long int val = digits[i] -'0';
/* check if any number in series contains 0 */
if(val == 0){
break;
}
mult = mult * val;
}
printf("mult is %lld\n",mult );
/* check for max value */
if(max < mult){
max = mult;
}
printf("the new max is %lld\n", max);
j += 1;
k += 1;
mult = 1;
printf("%d iteration finished\n", k);
}
printf("%lld\n", max);
You should use 'int64_t' at the place of 'int'
I have solve this problem using python 're' module
Finding all possible 13 digits number without having zeros (total 988 with zero and 283 without zero) then find the product of each of these digits and check for max
here i have used look ahead regex
Note: string must not contain any newline char
s = '731671765...'
import re
def product_13(d):
pro = 1
while d:
pro *= d % 10
d //= 10
return pro
pat = re.compile(r'(?=([1-9]{13}))')
all = map(int, re.findall(pat, s))
pro = -1
for i in all:
v = product_13(i)
if pro < v:
pro = v
print(pro)
**This is JavaScript solution.**
greatestProductOfAdjacentDigit = (givenNumber, noOfDigit) => {
stringNumberToNumbers = givenNumber => givenNumber.split('').map(each => parseInt(each, 10))
let numbers = mathematicalProblems.stringNumberToNumbers(givenNumber);
return numbers.map(function (each, ind, arr) {
return mathematicalProblems.productOfAll(arr.slice(ind, ind + noOfDigit));
}).reduce(function (accumulator, currentValue) {
return accumulator > currentValue ? accumulator : currentValue;
});
};
Testing
const givenNumber = '73167176531330624919225119674426574742355349' +
'194934969835203127745063262395783180169848018694788518438586' +
'156078911294949545950173795833195285320880551112540698747158' +
'523863050715693290963295227443043557668966489504452445231617' +
'318564030987111217223831136222989342338030813533627661428280' +
'644448664523874930358907296290491560440772390713810515859307' +
'960866701724271218839987979087922749219016997208880937766572' +
'733300105336788122023542180975125454059475224352584907711670' +
'556013604839586446706324415722155397536978179778461740649551' +
'492908625693219784686224828397224137565705605749026140797296' +
'865241453510047482166370484403199890008895243450658541227588' +
'666881164271714799244429282308634656748139191231628245861786' +
'645835912456652947654568284891288314260769004224219022671055' +
'626321111109370544217506941658960408071984038509624554443629' +
'812309878799272442849091888458015616609791913387549920052406' +
'368991256071760605886116467109405077541002256983155200055935' +
'72972571636269561882670428252483600823257530420752963450';
console.log(greatestProductOfAdjacentDigit(givenNumber, 4)); //5832
console.log(greatestProductOfAdjacentDigit(givenNumber, 13)); //23514624000
My 2 cents ... Javascript
Largest_product_in_series_13 = g => {
return [...g.matchAll(/(?=([1-9]{13}))/g)]
.reduce((a,c)=>(p=eval(c[1].split``.join`*`),p>a?p:a),0)
}
First it matches all 13 digit series, then it reduces to the biggest product.
console.log(Largest_product_in_series_13(`7316717653133062491922....
> 23514624000
start: 14.292ms
I solved it using ruby. if
x = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
then used below logic to solve the problem
def print_lps(x)
p = 1
0.upto(x.length-13) do |i|
j = i
xy = 1
while j < i+13 do
xy *= x[j].to_i
j += 1
end
p = xy if xy > p
end
puts p
end
print_lps(x) # 23514624000
I solve the problem using this approach
1.Run two loops first outer loop which iterate over numbers in the string.
2.Inner loop reach to next 13 numbers afterwards and store its product in a variable
3.As inner loop ends we only use maximum value.(that what we need) :>
Have a look at my code in C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s="//thestring is there";
long long unsigned mainans=1,ans=1; //initialize the value of mainans and ans to 1 (not 0 as product also become 0)
for(int i=0;i<s.length()-13;i++) //run the loop from 0 upto 13 minus string length
{
ans=1;
for(int j=i;j<i+13;j++) //now from that particular digit we check 13 digits afterwards it
{
int m=s[j]-'0'; //convert the number from string to integer
ans*=m; //taking product in every interation for 13 digits
}
mainans=max(mainans,ans); //now taking only max value because that what we need
}
cout<<mainans;
return 0;
}
This will find the answer in O(n) time and it handles zero. Written in Dart.
/**
* Main function
*
* Find the thirteen adjacent digits in the 1000-digit number that have the greatest product.
* What is the value of this product?
*
*/
const String DIGITS = "73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"12540698747158523863050715693290963295227443043557"
"66896648950445244523161731856403098711121722383113"
"62229893423380308135336276614282806444486645238749"
"30358907296290491560440772390713810515859307960866"
"70172427121883998797908792274921901699720888093776"
"65727333001053367881220235421809751254540594752243"
"52584907711670556013604839586446706324415722155397"
"53697817977846174064955149290862569321978468622482"
"83972241375657056057490261407972968652414535100474"
"82166370484403199890008895243450658541227588666881"
"16427171479924442928230863465674813919123162824586"
"17866458359124566529476545682848912883142607690042"
"24219022671055626321111109370544217506941658960408"
"07198403850962455444362981230987879927244284909188"
"84580156166097919133875499200524063689912560717606"
"05886116467109405077541002256983155200055935729725"
"71636269561882670428252483600823257530420752963450";
main(List<String> args) {
const int MAX_DIGITS = 13;
int len = DIGITS.length;
int digits = 0;
int largest = 0;
int current = 0;
int index = 0;
while (index < len) {
int value = int.parse(DIGITS[index]);
// if we get a zero then rebuild the MAX_DIGITS consecutive digits
if (value == 0) {
current = 0;
digits = 0;
} else {
// Multiply consecutive digits up to target set
if (digits < MAX_DIGITS) {
if (current == 0) {
current = value;
} else
current *= value;
digits++;
} else {
int divisor = int.parse(DIGITS[index - MAX_DIGITS]);
if (current == 0) {
current = value;
} else {
current = (current ~/ divisor);
current *= value;
}
}
if (current > largest) {
largest = current;
}
}
index++;
}
print('Num $largest');
}