I am just a beginner in PHP. I have tried to write a program for prime numbers, but the result is not correct. I couldn't find the error. How can I correct this? Here is my code:
<?php
$n=15;
for($i=2; $i<=$n; $i++)
{
echo "<br />";
for($j=2; $j<=$i-1; $j++)
{
$k=$i%$j;
if($k==0)
{
break;
}
else echo $i."is prime";
break;
}
}
?>
Try this:
<?php
$n=15;
for($i=2; $i<=$n; $i++)
{
$k = 1; //assume that it is prime
for($j=2; $j<$i; $j++) //if $i is 2, then it won't enter the loop as it will not match the condition ($j<$i)
{
$k=$i%$j;
if($k==0)
break; //if not prime, $k will be set as 0. So, break.
}
if($k!=0) // if $k <> 0, then it is prime
echo "<br />" . $i." is prime";
}
?>
Edit
Updated the code to take care of the "2"
Try this:(whitout using loop)
function is_prime($p) {
return ($p > 1) && (($p%2 >= 1) && ($p%3 >= 1) && ($p%5 >= 1)) || in_array($p, [2,3,5]);
}
echo is_prime(15);
You are breaking the loop the first time it's run by calling this basically:
if (something) {
break;
} else {
break;
}
it will break no matter what. you need to take out the last break.
Well, your code is kind of confusing to understand; at first glance it seems as if it's trying to determine primality by checking every divisor up to N, but you've got that outer-loop going on which I didn't see at first... Oh boy.
If you're just trying to figure out if some number N is prime, the following should work:
$n = 15
$prime = true;
for ($i = 2; $i < sqrt($n); $i++) {
if ($n % $i == 0) {
$prime = false;
break;
}
}
echo $n . " is " . ($prime ? "" : "not") . " prime.";
<?php
echo "TEST\r\n";
$n=15;
for($i=2; $i<=$n; $i++)
{
echo "I= $i \r\n";
for($j=2; $j<=$i-1; $j++)
{
$k = $i%$j;
if($k==0)
{
break;
} else {
echo $i."is prime \r\n";
}
break;
}
}
I think your secod for loop is incorrect.
for($i=2; $i<=$n; $i++) {
echo "<br />";
for($j=2; $j<=$i-1; $j++) {
...
The first value for $j is 2. And for the first time, the first value for $i is 2 again. Now, look at your second for loop code.
It will be like this at the first time:
for($j=2; $j<=2-1; $j++) ... // for($j=2; $j<=1; $j++)
And this condition is not valid at all: 2<=1
Related
I have this code that works but is missing some details
$input=7;
$k=($input+1)/2;
for($i=1;$i<=$input;$i++){
for($j=1;$j<=$input;$j++){
if($j==($input+1)/2 || $j==$k || $j==$input-$k+1){
echo "*";
}
else{
echo "-";
}
}
echo "<br>";
$k++;
}
And the output look like this
---*---
--***--
-*-*-*-
*--*--*
---*---
---*---
---*---
My desired output is
___*___
__***__
_*****_
*******
__***__
__***__
__***__
In your if statement you have three conditions. So there can only be three stars in a row.
I think your structure is more complex as it should be. You could use str_repeat instead. Something like this:
$input=7;
for($i=1;$i<=$input;$i+=2) {
echo str_repeat('-', ($input - $i) / 2 ) .
str_repeat('*', $i) .
str_repeat('-', ($input - $i) / 2 ) .
'<br>';
}
$shaft = floor($input / 2);
for($i=1;$i<$input/2;$i++) {
echo str_repeat('-', ($input - $shaft) / 2 ) .
str_repeat('*', $shaft) .
str_repeat('-', ($input - $shaft) / 2 ) .
'<br>';
}
The first loop draws the triangle which is growing by 2 each row.
The second loop draws the shaft.
So if you need to do it only using loops and if else, you have to elaborate your if statement. Here's my solution:
$input = 7;
for($i=1;$i<=2*$input;$i+=2) {
for($k=1;$k<=$input;$k++) {
if(($i <= $input && $k > floor(($input - $i)/2) && $k <= ceil(($input + $i)/2)) ||
($i > $input && $k > ceil($input/4) && $k <= floor(3/4*$input))) {
echo "*";
} else {
echo "-";
}
}
echo "<br>";
}
Note: In the first loop I use $i+=2, so with every iteration $i increases by two. To get the right number of lines the loop continues till 2*$input.
The if statement has two parts. In the first part the triangle is drawn (adding two stars every row since $i increases by 2). In the second part, when $i becomes greater than $input, drawing the shaft, which is half the width and 1/4 of the width on each side.
I got the answer guys, thank you all.
$x=($input/2); $y=$x+1; $w=($input/2);
if($w%2==0) {
$w++;
}
for($i=1; $i<=$input; $i++) {
for($j=1; $j<=$input; $j++) {
if($j>=$x && $j<=$y) {
echo "*";
}
else {
echo "_";
}
}
if($i>(($input-1)/2)) {
$x=(($input-$w)/2)+1;
$y=($x+$w)-1;
}
else {
$x--;
$y++;
}
echo "<br>";
}
i have this code .
echo "<br>";
$start = 1;
$angka = $_POST[angka];
$a = $angka;
for($i=$start; $i<=$angka; $i++) {
for($j=$start;$j<=$angka;$j=$j+2){
echo $i;
if($j < $angka) echo $a;
}
$a--;
echo '<br>';
}
Reference: Print Looping for dynamic row php
This is not my expecting result .
First i want the result like this .
-2-4-
1-3-5
-2-4-
1-3-5
-2-4-
The rule is Number of rows and columns follow the number of numbers declared.If the declaration of the number 5, then the results will be displayed are 5 rows and 5 columns like the example above.
i think this code is working
<?php
$_POST['angka'] = 5;
$angka = $_POST['angka'];
for($i=1; $i<=$angka; $i++) {
for($j=1;$j<=$angka;$j++){
if($i%2 == 1) {
if($j%2 == 0) {
echo $j;
} else {
echo '-';
}
} else {
if($j%2 == 0) {
echo '-';
} else {
echo $j;
}
}
}
echo '<br>';
}
Result:
-2-4-
1-3-5
-2-4-
1-3-5
-2-4-
Let's say I have this loop:
for($i = 1; $i <= 10; $i++){
if($i > 4){
echo 'Greater Than 4.' . '<br/>';
}
}
The previous loop will output the following:
Greater Than 4.
Greater Than 4.
Greater Than 4.
Greater Than 4.
Greater Than 4.
Greater Than 4.
As the condition is true 6 times.
What I want to do is to print this message only once so the output from the same loop and condition will be :
Greater Than 4.
I think this could be achieved by using a variable and give it this value at a specific point , But I don't know how to do it.
Well, it will be like your code expect that you print the message once:
$msg = 'There is no greater than 4';
for($i = 1; $i <= 10; $i++){
if($i > 4){
$msg = 'Greater Than 4.' . '<br/>';
// Make any additional required code here...
}
}
echo $msg;
;
Have you tried this :)
for($i=1;$i<=10;$i++){
echo ($i>4 && !isset($rslt))?$rslt='Greater Than 4.':'';
}
Or, you can loop first
then print the result
like this
$bucket = '';
for($i=1;$i<=10;$i++){
$bucket = ($i>4)?'Greater Than 4.':$bucket;
}
echo $bucket;
Hmmmm, I guess you case like this :D
$bucket = $condition = '';
$flag = 1;
for($i=1;$i<=10;$i++){
if($i>4){
$bucket = 'Greater Than 4. <br>';
$condition .= "Proses :{$flag}<br>";
$flag++;
//more condition process 6 times
}
}
echo $condition;
echo $bucket;
Or like this :D
$j=1;
for($i=1;$i<=10;$i++){
if($i>4){
if($i<=5){
echo 'Greater Than 4. <br>';
}
echo 'Proses '.($j++).'<br>';
//more condition process 6 times
}
}
Or, using the short hand
for($i= $j =0;$i<=10;$i++){
if($i>4){
echo ($i<=5)?'TheGreater Than 4. <br>':false;
$j++;
echo "Process number : {$j} <br>";
}
}
$run_once = true;
for($i = 1; $i <= 10; $i++){
if($i > 4 AND $run_once){
echo 'Greater Than 4.' . '<br/>';
$run_once = false;
}
}
you could also use if ($i == 4)
EDIT:
for($i = 1; $i <= 10; $i++){
if($i > 4){
if($i == 4){
echo 'this runs only once';
}
echo 'this runs every time';
}
}
I have the following bit of code and for some reason in the first WHILE loop the first value of $actor_list (when $i = 0) does not display. If I simply echo $actor_list[0] then it displays fine, but in the loop it will not display. I merely get [td][/td] as the output. The remaining values of the array display fine.
Also the line
echo '</tr><tr> </br>';
is not displaying.
What am I missing here? The value of $num_actors is an even number in my test scenario so there doesn't seem to be a reason for the above echo line to be skipped.
$actor_list = explode(" ", $actors);
$num_actors = count($actor_list);
if ($num_actors <= 6) {
foreach ($actor_list as $actor) {
echo '[td]'.$actor.'[/td] </br>';
}
} elseif ($num_actors <= 12) {
if ($num_actors % 2 == 0) {
$half_actors = $num_actors / 2;
while ($i <= ($half_actors - 1)) {
echo '[td]'.$actor_list[$i].'[/td] </br>';
$i++;
}
echo '</tr><tr> </br>';
while ($i <= $num_actors) {
echo '[td]'.$actor_list[$i].'[/td] </br>';
$i++;
}
}
}
You're not initialising the variable $i to 0, which means it will be set to 'null' and thus not reference the 0th index of the array; but when it's then incremented its value will become 1.
Note: [..] Decrementing NULL values has no effect too, but incrementing them results in 1.
See: http://php.net/manual/en/language.operators.increment.php
Try adding:
$i = 0;
before the if statement.
Made a few changes.
This is working for me.
Try it out.
<?php
$actor_list = 'act1 act2 act3 act4 act5 act6';
$actors = explode(" ", $actor_list);
$num_actors = count($actor_list);
//debug
//echo "<pre>";
//print_r($actor_list);
//echo "</pre>";
echo "<table>";
if ($num_actors <= 6) {
foreach ($actors as $actor) {
echo '<tr><td>'.$actor.'</td></tr>';
}
} elseif ($num_actors <= 12) {
if ($num_actors % 2 == 0) {
$half_actors = $num_actors / 2;
while ($i <= ($half_actors - 1)) {
echo '<tr><td>'.$actor_list[$i].'</td></tr>';
$i++;
}
while ($i <= $num_actors) {
echo '<tr><td>'.$actor_list[$i].'</td></tr>';
$i++;
}
}
}
echo "</table>";
?>
When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.