1
$\begingroup$

What would be another way to write this code in mathematica,but without using the code for and if? Is integer digits necessary foor this type of code?

b = 0;
For[i = 1, True, i++, b += Boole[BouncyQ[i]];
 If[b/i == 99/100, Break[]]]
i
$\endgroup$
3
  • 2
    $\begingroup$ Can you clarify what the code is expected to do? $\endgroup$ – Carl Lange Oct 4 '20 at 18:02
  • $\begingroup$ its suppose to follow project Euler problem 112 heree is the link, thank you! projecteuler.net/…. $\endgroup$ – Aran Oct 4 '20 at 18:28
  • $\begingroup$ my prof doesn't want us to use for and if yet $\endgroup$ – Aran Oct 4 '20 at 18:28
1
$\begingroup$

Euler projects are in general not easily to solve by brute force. Here is a program that does what you want. However, this program would run much too long. Euler projects should be solved by brain not PC:

Bouncy[n_] := (LessEqual[##] || GreaterEqual[##]) & @@ 
   IntegerDigits[n];
count = 0; i = 100;
While[count < i 99/100, count += Boole@Bouncy[i++]] ;
count
$\endgroup$
2
  • $\begingroup$ I believe you're missing a Not in your definition of Bouncy $\endgroup$ – Joshua Schrier Oct 4 '20 at 21:00
  • $\begingroup$ @Joshua Schrier You are right. $\endgroup$ – Daniel Huber Oct 5 '20 at 7:50
2
$\begingroup$

If your professor doesn't want you to use For and If yet, s/he may not want you to use advanced functional programming...such as the use of NestWhile...but here it goes anyway.

Assuming you have already defined BouncyQ,

(*evaluates the "next" (n+1) term and how many items are bouncy so far*)

bouncyWrapper[{n_, nBouncy_}] := {n + 1, nBouncy + Boole[BouncyQ[n + 1]]}


(* function that tests whether to stop *)

stopCriterion[threshold_][{n_, nBouncy_}] := (nBouncy/n) != threshold


(* perform the evaluation, stopping when the stopCriterion is True *)
NestWhile[
 bouncyWrapper, (*function to evaluate*)
 {1, 0}, (*initial condition*)
 stopCriterion[50/100] (*function that evaluates the stopping criterion*)
] (* {538, 269}*)

(* another example with 99/100 as the stop threshold *)
NestWhile[
 bouncyWrapper,
 {1, 0},
 stopCriterion[99/100]] (* {1587000, 1571130} *)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.