So i am trying to create a program that can find a number that can be divided by numbers 1-20. I know that i will have to use the following simple code concepts:
I know how loops work and how to create a loop that runs until a condition is met. Is there a simple was to run a loop until several conditions are met?
while ( condition1 && condition2 && condition3... ) {}
or
for ( int i = 0; i < n && condition1 && condition2... ) {}
Obviously these will loop while the conditions are true, not until the conditions are met. Its a simple change in the logic though to get the result you want
EDIT
Ane example of the kind of loop youre looking for could be like:
int number = ...;//initialized somewhere, this is what we're checking
BOOL divisible = YES;
for ( int i = 1; i <= 20 && divisible; ++i )
{
if ( (number % i) != 0 )
divisible = NO;//not divisible by i
}
Good answers in play, but I think it's good to mention the break operator in this discussion. Any loop, at any time, can be terminated using this operator. This can be helpful if you do not know all of the parameters which might go out-of-bounds, and you want to have a way of breaking the loop for reasons you may not have explicitly anticipated (i.e. perhaps your connection to a resource is no longer available...)
NSError *error = nil;
while(true) {
// run your app
if(error) {
break;
}
}
If a number is divisible by all numbers from 1 to 20 then it is divisible by the LCM of 1 to 20 so divisibility test is if(!(n%232792560)).
Further if m = pq | n then p|n, q|n so to explicitly test you only need to check for divisibility by primes. i.e if the number is not even then there is no need to check for divisibility by 4, 6, 8, 10, 12, 14, 16, 18 or 20. This reduces the test to the number being congruent to the 8th primorial = 9699690
OK, perhaps on second reading not as explicit as I should like: the expanded test looks like (by de Morgan's theorem)
if(!(n%19 || n%17 || n%16 || n%13 || n%11 || n%9 || n%7 || n%5))
// number is divisible by 1..20
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
I have a loop that doesn't exit and I need help converting a problem statement into a loop statement. Problem statement attached here:
#include <stdio.h>
int main(){
int num,last,newnum;
printf("ENTER YOUR NUMBER: ");
scanf("%d",&num);
while (num != 7 || num != -7 || num != 0){
last = num % 10;
last = last * 2;
num = num / 10;
num = num - last;
printf("%d",num);
}
}
You used the || operator when the && operator is the intended one. Let's look at why:
Say num == 0, then the loop should not execute but instead becomes an infinite loop.
If we solve the boolean condition like so:
true || true || false evaluates to true. The only case where it would evaluate to false would be if num equalled 7, -7, and 0 simultaneously, which is impossible. Plugging a sample value into the boolean condition is a good tool for figuring out why your loop ends too early or goes on too long.
while (num != 7 && num != -7 && num != 0)
This ^ is what your loop should be. However, as I was testing it, it seemed to get stuck in infinite loops regardless. That is because the loop body won't always result in 7, -7, or 0, as not every number is divisible by 7. The number 499443, divisible by 7, didn't produce an infinite loop, but the number 2, which is not, did.
Also, indent your code in the future, as it can make debugging easier.
If you need a more practical way to check if a number is divisible by 7, then you can use:
if (num % 7 == 0) {
// Divisible by 7
}
Isn't order of execution generally from left to right in Raku?
my #a = my #b = [9 , 3];
say (#a[1] - #a[0]) == (#b[1] R- #b[0]); # False {as expected}
say (#a.pop() - #a.pop()) == (#b.pop() R- #b.pop()); # True {Huh?!?}
This is what I get in Rakudo(tm) v2020.12 and 2021.07.
The first 2 lines make sense, but the third I can not fathom.
It is.
But you should realize that the minus infix operator is just a subroutine under the hood, taking 2 parameters that are evaluated left to right. So when you're saying:
$a - $b
you are in fact calling the infix:<-> sub:
infix:<->($a,$b);
The R meta-operator basically creates a wrap around the infix:<-> sub that reverses the arguments:
my &infix:<R->($a,$b) = &infix:<->.wrap: -> $a, $b { nextwith $b, $a }
So, if you do a:
$a R- $b
you are in fact doing a:
infix:<R->($a,$b)
which is then basically a:
infix:<->($b,$a)
Note that in the call to infix:<R-> in your example, $a become 3, and $b becomes 9 because the order of the arguments is processed left to right. This then calls infix:<->(3,9), producing the -6 value that you would also get without the R.
It may be a little counter-intuitive, but I consider this behaviour as correct. Although the documentation could probably use some additional explanation on this behaviour.
Let me emulate what I assumed was happening in line 3 of my code prefaced with #a is the same as #b is 9, 3 (big number then little number)
(#a.pop() - #a.pop()) == (#b.pop() R- #b.pop())
(3 - 9) == (3 R- 9)
( -6 ) == ( 6 )
False
...That was my expectation. But what raku seems to be doing is
(#a.pop() - #a.pop()) == (#b.pop() R- #b.pop())
#R meta-op swaps 1st `#b.pop()` with 2nd `#b.pop()`
(#a.pop() - #a.pop()) == (#b.pop() - #b.pop())
(3 - 9) == (3 - 9)
( -6 ) == ( -6 )
True
The R in R- swaps functions first, then calls the for values. Since they are the same function, the R in R- has no practical effect.
Side Note: In fuctional programming a 'pure' function will return the same value every time you call it with the same parameters. But pop is not 'pure'. Every call can produce different results. It needs to be used with care.
The R meta op not only reverses the operator, it will also reverse the order in which the operands will be evaluated.
sub term:<a> { say 'a'; '3' }
sub term:<b> { say 'b'; '9' }
say a ~ b;
a
b
ab
Note that a happened first.
If we use R, then b happens first instead.
say a R~ b;
b
a
ba
The problem is that in your code all of the pop calls are getting their data from the same source.
my #data = < a b a b >;
sub term:<l> { my $v = #data.shift; say "l=$v"; return $v }
sub term:<r> { my $v = #data.shift; say "r=$v"; return $v }
say l ~ r;
l=a
r=b
ab
say l R~ r;
r=a
l=b
ab
A way to get around that is to use the reduce meta operator with a list
[-](#a.pop, #a.pop) == [R-](#a.pop, #a.pop)
Or in some other way make sure the pop operations happen in the order you expect.
You could also just use the values directly from the array without using pop.
[-]( #a[0,1] ) == [R-]( #a[2,3] )
Let me emulate what happens by writing the logic one way for #a then manually reversing the operands for #b instead of using R:
my #a = my #b = [9 , 3];
sub apop { #a.pop }
sub bpop { #b.pop }
say apop - apop; # -6
say bpop - bpop; # -6 (operands *manually* reversed)
This not only appeals to my sense of intuition about what's going on, I'm thus far confused why you were confused and why Liz has said "It may be a little counter-intuitive" and you've said it is plain unintuitive!
I am trying to do this simple while loop but it's not working. The compiler is not giving any type of error or warning but when i try to run my function it ends up in an infinite loop:
let example x =
let k = ref x in
while (!k > 42) do
if ( (!k mod 5) == 0) then (
k:= !k/2
);
done;
if(!k<42) then (
Printf.printf "k is less than 42"
);
if(!k == 42) then (
Printf.printf "k is equal to 42"
)
;;
Well, your loop only modifies !k when !k mod 5 = 0. If !k isn't divisible by 5, it will never change in value. This suggests that the loop will either run 0 times or will run an infinite number of times.
You don't show any calls to example, but any call where you pass a value > 42 and not a multiple of 5 should loop infinitely it seems to me.
By the way, this is what #user2864740 was trying to point out. 43 is a value > 42 that's not divisible by 5.
(As a side comment, you should use = to compare values for equality. The == operator in OCaml is useful in limited cases. This often causes problems for people coming from other languages.)
* > 20 && * %% 5 used in grep seems wrong, does is equal to a WhateverCode lambda that takes 2 arguments? As this explain on SO
> my #a = 1,12,15,20,25,30,35,37;
> #a.grep: * > 20 && * %% 5 # The result seems strange, expected (25 30 35)
(15 20 25 30 35)
> #a.grep: * %% 5 && * > 20
(25 30 35 37)
> #a.grep: { $_>20 && $_ %% 5 }
(25 30 35)
> #a.grep: all(* > 20, * %% 5)
(25 30 35)
> #a.grep: -> $a { all($a > 20, $a %% 5) }
(25 30 35)
> #a.grep: -> $a {$a > 20 && $a %% 5}
(25 30 35)
Golfed
my &or = * == 1 || * == 2 ;
my &and = * == 1 && * == 2 ;
say .signature, .(1), .(2)
for &or, ∧
displays:
(;; $whatevercode_arg_1 is raw)TrueFalse
(;; $whatevercode_arg_4 is raw)FalseTrue
I still don't know what's going on [ed: that is, I didn't at the time I wrote this paragraph; I kept what I wrote in this answer as the mystery unfolded], but it's clear that the signature is for just one arg and the result is as per just the right hand expression for the &and and the left hand for the &or which means the code doesn't seem to have, er, left the result that's, er, right. Investigation continues... (and no, I'm not det remiker).
Mystery solved
So, it looks like the logical ops (&&, ||, and, or, etc.) don't do Whatever-currying. Which is fair enough given that "not all operators and syntactic constructs curry * (or Whatever-stars) to WhateverCode". Logical, even, given their nature. They probably ought to be added to the table of exceptions on that page though.
In the meantime, operators like == do Whatever curry. Again, that's fair enough given "subexpressions may impose their own Whatever star rules".
So it makes sense that &or and &and turn in to...
Aha! Got it. The * == 1 and * == 2 are evaluated at compile-time and turn into WhateverCodes. As WhateverCodes they are just bits of code. They are defined. They are True. (This ignores calling them at run-time.) Then along comes the && and evaluates to the right hand WhateverCode. (The || would evaluate to its left hand WhateverCode.)
Hence the behavior we see.
A solution
Per prompting by #HåkonHægland, the code that would work is therefore code that doesn't rely on logical ops Whatever-currying, i.e.:
my #a = 1,12,15,20,25,30,35,37;
say #a.grep: { $_ > 20 && $_ %% 5 } # (25 30 35)
Now what?
Now we have to figure out what doc edits to propose...
Actually, before we do that, confirm that logical ops are supposed to not Whatever-curry...
And to start that ball rolling, I just trawled the results of a search for TimToady comments on #perl6 about "currying" (there were none on #perl6-dev), looking for ones pertinent to the case we have here.
First, one from 2017 that's arguably relevant to any doc edits:
the design docs actually try to avoid the word "currying" ... but it's hard to get people to use words differently than they do
Next, one from 2015 about && and || and such:
|| and && and such are really control flow operators, turned rather rapidly into 'if' and 'unless' ... those ops can be curried with .assuming, I assume
And finally a couple from 2010 that also seem potentially important (though perhaps one or more are no longer applicable?):
all operators autocurry a WhateverCode, whether or not they curry a Whatever
I think we can keep the current mechanism as a fallback for operators that still want to curry at run time
> my $d = * + * + *
> $d.arity
3
> my $e = * == 1 || * == 2 || * == 3
> $e.arity
1
as the doc say:
Returns the minimum number of positional arguments that must be passed in order to call the code object.
so I think the all three star in * == 1 || * == 2 || * == 3 is the same thing.
> my $e = * == 1 && * == 2 && * > 3
> $e(1)
False
> $e(2)
False
> $e(3)
False
> $e(4)
True
I'm studying Obj-C and now I'm not understand why my loop isn't work how it should. I know a way i could achieve result with single while loop, but i want to do this through do while and can't figure out whats going wrong.
What i want is, to show integer called triangularNumber for integers 5,10,15.. and so on. There is what i've tried:
for (int i=1; i<51; i++){
int triangularNumber;
do {
triangularNumber = i * (i+1)/2;
NSLog(#"Trianglular number is %i", triangularNumber);
}
while (i%5 == 0);
}
It produce odd results:
1) Condition of i%5==0 is not met, it output 1,3,6,10 then infinite numbers of 15
2) It create an infinite loop
Please tell me, what is wrong in that code and how to fix it. Thanks!
Instead of do while loop within for loop, use if to check whether a number is divisible by 5 or not.
If you want to do it with do while loop, you could do the following:
int i = 5;
int triangularNumber;
do {
triangularNumber = i * (i+1)/2;
NSLog(#"Trianglular number is %i", triangularNumber);
i += 5;
} while (i < 51);
Reason your code is not working:
Within your do while loop, if i say is 5, then you will end up running in infinite loop as you will satisfy your do while loop's condition which is i%5==0
You just need numbers like 5, 10, 15.. so it's just matter of one loop. Now loop starts with 1 till 50, and you are picky in the sense you just need one element of 5, hence to be picky you could use if condition which says print if and only if my i is multiple of 5.
Do while will always enter into loop and will execute it once. So for 1 it will enter and do calculation for triangularNumber as 1 * 2 /2 = 1 and hence your output 1 and checks condition post printing is 1 divisible by 5, no then it comes out and increments i to 2 and follows same routine as above.