Fill array with first 100 prime numbers using loop - php

I have been working on a php function to create an array of prime numbers. So far I have it working to where it lists all the primes from 2 to 1000. What I want to do now is generate the first 100 prime numbers by using the increment count < 100 or something similar. Here is my current code.
<?php
function prima($n)
{
$primeNumbers = []; // Initiate result array
for ($i = 1; $i <= $n; $i++)
{
$counter = 0;
for ($j = 1; $j <= $i; $j++)
{
if ($i % $j == 0)
{
$counter++;
}
}
if ($counter == 2)
{
$primeNumbers[] = $i; // store value to array
}
}
return json_encode($primeNumbers); // return converted json object
}
header('Content-Type: application/json'); // tell browser what to expect
echo prima(1000); // echo the json string returned from function
?>

At the end of the for loop, add 'if (count($primeNumbers) == 100) break;'

Related

Project Euler #3 - Getting weird fatal error

I'm working on Project Euler problem 3, but my code gives a weird error. The error is:
Fatal error: Can't use function return value in write context in
D:\Google Drive\ITvitae\PHP5\ProjectEuler\PE3-PrimeFactor2.php on line
52
This is the code I'm running:
<html>
<body>
<?php
ini_set('memory_limit', '1024M');
ini_set('set_time_limit', '120');
$max = 1000000;
#$max = 600851475143;
$primes = array();
// Define sqrt ceiling
$maxSqrt = ceil(sqrt($max));
function isPrime($num) {
// 1 is not prime
if ($num == 1)
return false;
// 2 is prime
if ($num == 2)
return true;
// Removes all even numbers
if ($num % 2 == 0) {
return false;
}
// Check odd numbers, if factor return false
// The sqrt can be an aproximation, round it to the next highest integer value.
$ceil = ceil(sqrt($num));
for ($i = 3; $i <= $ceil; $i = $i + 2) {
if($num % $i == 0)
return false;
}
return true;
}
//Push latest prime into array
for ($i = 2; $i <= $maxSqrt; $i++) {
if (isPrime($i)) {
array_push($primes, $i);
}
}
// Check whether $max is divisible by $primes($j)
for ($j = 0; $j <= count($primes); $j++) {
if ($max % $primes($j) = 0) {
$max = $max / $primes($j);
}
}
//echo "<pre>";
//var_dump($primes);
//echo "</pre>";
echo array_pop($primes);
?>
</body>
</html>
Line 52 being
if ($max % $primes($j) = 0) {
Under // Check whether $max is divisible by $primes($j)
I've never seen this error before, and I don't understand why it's giving it. In my head, the logic is flawless (which inevitably, therefore it isn't). What is going wrong here?
EDIT: Changed it to
if ($max % $primes($j) == 0) {
But it tells me the Function name must be a string. I don't understand.
The first problem was, you used = for comparison. = is an assignment and you couldn't assign a value to an expression (that wouldn't have a usefull meaning..)
Second, you have to use [] for array access, instead of (). Using () after an identifier or var always tries to call an function. In your case $primes is an array, which isn't a function.
Third, you should fix the of-by-one array access error in your for-loop.
for ($j = 0; $j < count($primes); $j++) { // < instead of <=
if ($max % $primes[$j] == 0) { // == instead of = and [] instead of ()
$max = $max / $primes[$j]; // again [] instead of ()
}
}

I dont know what to do with this PHP Code

The code below basically helps in finding out if a number is a Palindromic Number or not. Although I get my execution done with the output, I just can seem to handle all the "screams" and fatal errors that I get. How do I handle this. Just a beginner and trust you can explain in a way that I may be able to understand..
<?php
for ($num = 1; $num <= 20; ++$num){
$_array1 = str_split($num);
//print_r($_array1);
//echo "<br/>";
$_array2 = array_reverse($_array1);
//print_r($_array2);
//echo "<br/>";
$i = 0;
$j = 0;
while ($i < sizeof($_array1) && $j < sizeof($_array2)){
if ($_array1[$i] == $_array2[$j]){
++$i;
++$j;
}
}
if ($_array1[$i] == $_array2[$j]){
echo "The number $num is a Palindrome Number";
}
}
?>
You get to the size of elements, which is 1. However, if your array has only one element, which is the case for 1-digit numbers, then sizeof($_array) === 1. Which means that the biggest possible index you can use is 0. You need to change your code to something like this:
<?php
for ($num = 1; $num <= 20; ++$num){
$_array1 = str_split($num);
//print_r($_array1);
//echo "<br/>";
$_array2 = array_reverse($_array1);
//print_r($_array2);
//echo "<br/>";
$i = 0;
$j = 0;
$different = false;
while ((!$different) && ($i < sizeof($_array1))){
if ($_array1[$i] == $_array2[$j]){
++$i;
++$j;
} else {
$different = true;
}
}
if (!$different){
echo "The number $num is a Palindrome Number";
}
}
?>
But you are inversing the array without a need to do so and you are looping for unnecessarily long. I propose this function to determine whether an array is a palindrome:
function isPalindrome($input) {
$size = count($input);
for ($index = 0; $index < $size / 2; $index++) {
if ($input[$index] != $input[$size - $index - 1]) {
return false;
}
}
return true;
}
Note, that:
the function assumes that the keys of the array are numbers
the function uses a single array
the size of the array is stored into a local variable to not calculate it repeatedly
the cycle cycles until half of the array, since going beyond that is unnecessary, due to the symmetrical nature of the != operator
the function returns false when the first difference is found, to further optimize the checking
if there were no differences, the function returns true, representing that the input is a palindrome

PHP for loop within for loop with different incrementing values

I am new to PHP and for loops but I am having trouble racking my brain around the math for this. I am trying to write a loop that will create an array with 49 items. The items have two incrementing values within them. The 49 items are below:
M1s1t1url
M1s1t2url
M1s1t3url
M1s1t4url
M1s1t5url
M1s1t6url
M1s1t7url
M1s2t1url
M1s2t2url
M1s2t3url
M1s2t4url
M1s2t5url
M1s2t6url
M1s2t7url
M1s3t1url
M1s3t2url
M1s3t3url
M1s3t4url
M1s3t5url
M1s3t6url
M1s3t7url
M1s4t1url
M1s4t2url
M1s4t3url
M1s4t4url
M1s4t5url
M1s4t6url
M1s4t7url
M1s5t1url
M1s5t2url
M1s5t3url
M1s5t4url
M1s5t5url
M1s5t6url
M1s5t7url
M1s6t1url
M1s6t2url
M1s6t3url
M1s6t4url
M1s6t5url
M1s6t6url
M1s6t7url
M1s7t1url
M1s7t2url
M1s7t3url
M1s7t4url
M1s7t5url
M1s7t6url
M1s7t7url
As you can see there are three numbers in each item. The first number is a constant. The second number counts up to 7 then resets back to 1. The third number adds 1 every time the second number resets back to 1. Here is what I have below but I know I am off on the calculations.
for ($i = 1; $i < 8; $i = $i + 1) {
for ($u = 1; $u < 8; $u = $u + 1) {
$urln[] = 'M1s'.[$u].'t'.[$i].'url';
}
}
I am getting an array to string error.
<?php
for ($i = 1; $i < 8; $i++) {
for ($u = 1; $u < 8; $u++) {
$urln[] = 'M1s' . $u . 't' . $i . 'url';
}
}
<?php
$urln = array();
for ($i = 1; $i < 8; $i++) {
for ($u = 1; $u < 8; $u++) {
$urln[] = 'M1s' .$i. 't'. $u .'url';
}
}
foreach ($urln as $i) {
echo "$i\n";
}
?>

I need to find all amicable numbers up to a certain number

Here is my code:
$n = 300;
$set = 0;
$set2 = 0;
for($i = 1; $i<$n; $i++)
{
for($j = 1; $j <$i; $j++)
{
$qol = $i % $j;
if($qol == 0)
{
$set += $j;
}
}
for($s=1; $s<$set; $s++)
{
$qol2 = $set % $s;
if($s == 0)
{
$set2 += $s;
}
}
if($set2 == $i)
{
echo "$set and $i are amicable numbers</br>";
}
}
I do not know what the heck the problem is!
FYI: 220 and 284 are an example of amicable numbers. The sum of the proper divisors of one number are equal to other number and vice versa (wiki).
I am having troubles following your logic. In your code how would $set2 == $i ever be true? Seems to me that $i would always be greater.
I would do it the following way:
First make a separate function that finds the sums of the proper divisors:
// Function to output sum of proper divisors of $num
function sumDiv($num) {
// Return 0 if $num is 1 or less
if ($num <= 1) {
return 0;
}
$result = 1; // All nums divide by 1
$sqrt = sqrt($num);
// Add divisors to result
for ($i = 2; $i < $sqrt; $i++) {
if ($num % $i == 0) {
$result += $i + $num / $i;
}
}
// If perfect square add squareroot to result
if (floor($sqrt) == $sqrt) {
$result += $sqrt;
}
return $result;
}
Next check each iteration for a match:
$n = 1500;
for ($i = 1; $i < $n; $i++) {
// Get sum of proper devisors of $i, and sum of div. of result.
$currentDivs = sumDiv($i);
$resultDivs = sumDiv($currentDivs);
// Check for a match with sums not equal to each other.
if ($i == $resultDivs && $currentDivs != $resultDivs) {
echo "$i and $currentDivs are amicable numbers<br>";
}
}
Here a functioning phpfiddle.
Warning: Large numbers will take very long to process!

php array output problem

In php is there a function to increment the
values of subsequent values twice(*2) in an array
column based on an initial value?
$beta = array(
array('5', '1''1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2')
);
/*Example: '5' will be '10' (5*2 =10 and output 10 to web)
'2' will be '4' (2*2 = 4 and output 4 to web)
The next '2' will be '16' (4*2 = 8 and output 8 to web)
The next '2' will be '32' (8*2 = 16 and output 16 to web)
And so forth? */
Furthermore is there an easier way to construct this array, cause I firmly believe there is, but not something too complicated in terms of construct such that a noob will not understand it, again thanks.
[Disclaimer: I have spent 3 days trying to understand arrays, I now understand them; however, I am still new and am currently having some issues when trying to manipulate the values in my array and output them to the web.And I am still pretty sure I have a lot to read and learn, so please no flamers, I just need some help, found this problem in this C++ book:
[http://books.google.com/books?id=4Fn_P7tdOZgC&pg=PT424&lpg=PT424&dq=subsequent+++column+is+twice+the+value&source=bl&ots=gSvQ_LhxoI&sig=dG_Ilf1iLO86lqX936cT1PpkPc8&hl=en&ei=OEEBS_eODYyotgOFtJD3CQ&sa=X&oi=book_result&ct=result&resnum=1&ved=0CAgQ6AEwAA#v=onepage&q=subsequent%20%20%20column%20is%20twice%20the%20value&f=false][1]
You can try array_map:
<?php
function increase($n) {
return is_array($n) ? array_map('increase', $n) : $n * 2;
}
$new_beta = array_map("increase", $beta);
As for constructing the array, there are other methods to do so but I believe this is the most performent and clean.
Here is an answer for each question in that section of the book, enjoy!
<?php
// Declare an array alpha of 10 rows and 20 columns of type int
// Initialise the array alpha to 0
$alpha = array(array());
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
$alpha[$i][$j] = 0;
}
}
// Store 1 in the first row and 2 in the remaining rows
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
if($i == 0)
{
$alpha[$i][$j] = 1;
}
else
{
$alpha[$i][$j] = 2;
}
}
}
// Store 5 in the first column, and make sure that the value in
// each subsequent column is twice the value in the previous column
// (Beware this doesn't build off the initial value of 5 in the first
// column but the previously set values above)
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
if($j == 0)
{
$alpha[$i][$j] = 5;
}
else
{
if($j - 1 >= 1)
{
$alpha[$i][$j] = $alpha[$i][$j-1] * 2;
}
}
}
}
// Print the array alpha one row per line
print "Printing the array alpha one row per line:<br/>";
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
print "[". $alpha[$i][$j] ."] ";
}
print "<br/>";
}
print "<br/>";
// Print the array alpha one column per line
print "Printing the array alpha one column per line:<br/>";
for($j = 0; $j < 20; $j++)
{
for($i = 0; $i < 10; $i++)
{
print "[". $alpha[$i][$j] ."] ";
}
print "<br/>";
}
?>

Categories