File tree 2 files changed +61
-0
lines changed
ProjectEulerProblems/Problem 8
2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ using ProjectEulerProblems . Problem_8 ;
2
+ using Xunit ;
3
+
4
+ namespace ProjectEulerProblems . Tests . Tests ;
5
+
6
+ public class Problem8Tests {
7
+ public readonly string _data =
8
+ "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450" ;
9
+
10
+ [ Theory ]
11
+ [ InlineData ( 5832 , 4 ) ] //digits 9989
12
+ [ InlineData ( 23514624000 , 13 ) ]
13
+ public void Problem7Test ( long expected , int digits ) {
14
+ var sut = new Lib ( ) ;
15
+ var actual = Lib . GreatestProduct ( _data , digits ) ;
16
+
17
+ Assert . Equal ( expected , actual ) ;
18
+ }
19
+ }
Original file line number Diff line number Diff line change
1
+ namespace ProjectEulerProblems . Problem_8 ;
2
+
3
+ public class Lib {
4
+ public static long GreatestProduct ( ReadOnlySpan < char > data , int digits ) {
5
+ var maxSum = 0L ;
6
+ var currentSum = 0L ;
7
+
8
+ var maxProduct = 1L ;
9
+
10
+ var _digits = new int [ digits ] ;
11
+
12
+ for ( var i = 0 ; i < _digits . Length ; i ++ ) {
13
+ maxSum += data [ i ] - '0' ;
14
+ maxProduct *= data [ i ] - '0' ;
15
+ _digits [ i ] = data [ i ] - '0' ;
16
+ }
17
+
18
+ currentSum = maxSum ;
19
+
20
+ for ( var i = 0 ; i < data . Length - digits ; i ++ ) {
21
+ currentSum -= data [ i ] - '0' ;
22
+ currentSum += data [ i + digits ] - '0' ;
23
+
24
+ if ( maxSum < currentSum ) {
25
+ var tempArray = new int [ digits ] ;
26
+ var tempMaxproduct = 1L ;
27
+ for ( var j = 0 ; j < tempArray . Length ; ++ j ) {
28
+ tempArray [ j ] = data [ i + j + 1 ] - '0' ;
29
+ tempMaxproduct *= data [ i + j + 1 ] - '0' ;
30
+ }
31
+
32
+ if ( tempMaxproduct > maxProduct ) {
33
+ maxProduct = tempMaxproduct ;
34
+ _digits = tempArray ;
35
+ maxSum = currentSum ;
36
+ }
37
+ }
38
+ }
39
+
40
+ return maxProduct ;
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments