Pari GP - Checking if user keyed in a prime number - primes

I am currently learning how to use Pari GP and right now i am trying to write out a code on checking whether if the user did key in a prime number or not.
Here is my code.
printf("\t%s \n","PrimeNo(P): To check if it is a prime or not");
PrimeNo(p)={
if(isprime(p)||1, print("Prime numbers only"));
if(isprime(p)||0, print("Prime numbers stored"));
print(p);
}
Problem is my first "if" line works by identifying that it was not a prime, but when i key in a prime number, both line appeared.
Would appreciate if anyone can help.

Your if statements have two tests each, so both are true if p is prime (the first if isprime(p) OR 1, the second if isprime(p) OR 0). I think you want something like:
PrimeNo(p) = { if( isprime(p), print("Yep"), print("Nope") ); print(p); }
Here we're using the if-then-else form of Pari/GP's if, so we do the first item if isprime(p) is true and the second item if it is false. This also has the advantage of only calling isprime once, which is important if your numbers are large (one can also debate ispseudoprime vs. isprime but there is no difference for 64-bit inputs).

Related

How to generate derivative list with frequencies

I have some C++ code that picks a random item from a list. I need it to weight that randomness so that an item at place "n" has a chance equal to x/n where "x" is the chance that item one in the list will be selected. My current code is like this:
srand(time(NULL));
string a[≈9000] = {"String#1", "String#2", . . ., "String #≈9000"};
int value = rand() % ≈9000;
cout << a[value]
Note that the number notated as "≈9000" is a precise integer obscured for confidentiality. Variable names may be changed.
How can I weight it? I've come up with an equivalent formula
List B[≈9000] = "Item 'n' of 'a' times ≈9000 ÷ n"
Though you might notice that that isn't accurate CPP notation. Do y'all have any ideas how I can implement this?
This is not possible.
You need somehow to allow a variation on your conditions to have a proper distribution.

How can I check if two cells are equal in brainf*ck?

How can I check if the value in cell #0 is equal to the value in cell #1? I am trying to write code equivalent to:
if(a == b)
{
//do stuff
}
else
{
//do something else
}
I have read Brainfuck compare 2 numbers as greater than or less than, and the second answer gave me a general idea of what I'd need to do, but I cannot figure it out. (That solution gives if a < b, else.)
I am thinking I need to do something along the lines of decrementing both values, and if they reach 0 at the same time, then they are true. But I keep getting stuck at the same exit point every time I think about it.
How can I check if two cells are equal in brainfuck?
I think I have it, I'm not a brainfuck expert but this question looked interesting. There might be a simpler way to do it, but I went with your method of decrementing values one by one.
In this case, if the two values in cell 0 and 1 are equal jump a ton forward, if they are not equal jump a little forward (second brackets is the not equal case, third brackets is the equal case)
Note that I'm using brainfucks while statements as a ghetto if (cell != 0)
+++++++++++++++++
>
+++++++++++++++++
>+<
[ - < - >] <[>>>>>] >> [>>>>>>>>>>>>>>>>>>>>>]
Try it online: http://fatiherikli.github.io/brainfuck-visualizer/#KysrKysrKysrKysrKysrKysKPgorKysrKysrKysrKysrKysrKwo+KzwKWyAtIDwgLSA+XSA8Wz4+Pj4+XSA+PiBbPj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+XQoKCg==
An example implementation, print T (true) if the two values are equal, F (false) if they are not equal
http://fatiherikli.github.io/brainfuck-visualizer/#KysrCj4KKysrKwo+KzwKWyAtIDwgLSA+XSA8Wz4+PgorKysrKysrKysrKysrKysrKysrKworKysrKysrKysrKysrKysrKysrKworKysrKysrKysrKysrKysrKysrKworKysrKysrKysrCi4KPgoKXSA+PiBbCisrKysrKysrKysrKysrKysrKysrCisrKysrKysrKysrKysrKysrKysrCisrKysrKysrKysrKysrKysrKysrCisrKysrKysrKysrKysrKysrKysrCisrKwouCj4KXQ==
+>>(a+++++)>(b+++++)>>+<<<
[[->]<<]
<
[>>>>>-<<<<<
a>b
]
>>
[->>-<
a<b
]
>>
[-
a=b
]
Pointer ends on the same pointer in the same state but the code within the appropriate brackets has been executed.
I came up with this for my bf compiler thing
basically it subtracts and then checks if the result is 0.
Can be easily changed to execute stuff in if/else-ish way
Layout:
[A] B
>[-<->]+<[>-<[-]]>
Output
0 [result]
Result is 1 if equal

C++ Modulus Operator Understanding

I am just starting out programming and reading thru C++ Programming Principles and Practice. I am currently doing the Chapter 3 exercises and do not understand why this code I wrote works. Please help explain.
#include "std_lib_facilities.h"
int main() {
cout<<"Hello, User\n""Please enter a number (Followed by the 'Enter' key):";
int number=0;
cin>> number;
if (number%2) {
cout<<"Your number is an odd number!";
} else {
cout<<"Your number is an even number\n";
}
return 0;
}
When number is odd, number%2 is 1.
if (number%2) {
is equivalent to
if (1) {
Hence, you get the output from the line
cout<<"Your number is an odd number!";
When number is even, number%2 is 0.
if (number%2) {
is equivalent to
if (0) {
Hence, you get the output from the line
cout<<"Your number is an even number\n";
The modulus operator simply determines the remainder of the corresponding division problem. For instance, 2 % 2 returns 0 as 2 / 2 is 1 with a remainder of 0.
In your code, any even number entered will return a 0 as all even numbers are, by definition, divisible by 2 (meaning <any even number> % 2 == 0)
Likewise, any odd number entered will return 1 (for instance, 7 % 2 == 1 as 7 / 2 has a remainder of 1).
In c++, like in many programming languages, numeral values can be treated as booleans such that 0 relates to false while other numbers (depending on the language) relate to true (1 is, as far as I know, universally true no matter the programming language).
In other words, an odd number input would evaluate number % 2 to 1, meaning true. So if (number % 2), we know that the input number is odd. Otherwise, number % 2 must be false, meaning 0, which means that the input number is even.
"if" statements works on boolean values. Let's remember that boolean values are represented by "false" and "true", but in reality, it's all about the binary set of Z2 containing {0, 1}. "false" represents "0" and "true" represents "1" (or some people in electronics interpret them as "off/on")
So, yeah, behind the curtains, "if" statements are looking for 0 or 1. The modulus operator returns the rest of a / b. When you input any number and divide it by 2, you are gonna get a rest of 0 or 1 being it pair or an odd number.
So that's why it works, you will always get a result of 0 or 1 which are false and true by doing that operation that way.
think of modulus in terms of this:
while (integer A is bigger than integer B,)
A = A - B;
return A
for example, 9%2 -> 9-2=7-2=5-2=3-2=1
9%2=1;
the statement if (number%2) is what is called a boolean comparison (true false). Another way to write this statement identically is if(number%2 != 0) or if(number%2 != false) since false and zero are equivocal. You're taking the return value of the modulus operator function (a template object we will assume is an integer) and inserting it into an if statement that executes if the input does not equal zero. If statements execute if the input is -5,9999999,1-- anything but zero. So, if (2) would be true. if(-5) would also be true. if(0) would be false. if(5%2) would be 1 = true. if(4%2) would be if(0) = false. If it is true, the code in the body of the if statement is executed.

How do I convert this function into a loop?

I have an array of letters of an unknown number of elements which contains lower case letters. I have written a function for converting a lower case number to its ASCII value
int returnVal (char x)
{
return (int) x;
}
I am trying to combine all of these values into one number. Subtracting 87 from each of these means that the value is always a 2 digit number. I am able to combine an array made up if two elements by:
returnVal (foo[0]) - 87) + returnVal (foo[1] - 87) * 100
an array made up of three elements by
returnVal (foo[0]) - 87) + returnVal (foo[1] -87) * 100 + returnVal (foo[2] - 87) * 100 * 100
I am multiplying each element by 100^its position in the array and summing them. This means that [a,b,c] would become 121110 (yes, the 'flip' having the value for 'c' first and 'a' last is intentional). Could anybody programme this (for an array of an unknown number of elements)?
EDIT: I have received no form of schooling at programming/computer science at any pojnt in my life, this is not homework. I am trying to teach myself and I have got stuck; I don't know anybody in person who I could go to for help so I asked here, apologies to those of you who are offended.
EDIT2: I know that this opinion is going to annoy a lot of people; what is the purpose of stackoverflow.com if it is not to exchange information? If I were a child who was stuck with my homework (I'm not) surely that is a valid reason for using stack overflow? Many people on this website seem to have the mindset that if a problem is asked by a beginner then it is not worth answering, which is completely fine because your time is your own. However, what genuinely bugs me is the people who see a question which they deem trivial and say "homework" and vote it down immediately. I think that this website would be far better if there wasn't an "minimum-level" knowledge required in order to ask questions, the "elitist" mindset is just childish in my opinion.
Since this is a learning exercise, here are some hints for you to complete the task yourself:
Prepare a value that will server as the "running total" for your number so far.
Start the running total at zero.
When you convert a number, say, "1234", to an int, this value would first become 1, then 12, then 123, and finally 1234
The final value of the running total is your end result
To go from a previous value to the next, multiply the prior value by ten, and add the value of the current digit to it
Your returnVal does not make sense, because in C you can very often avoid an explicit conversion of char to int. You can definitely avoid it in this case.
Making a function int digit(char c) that returns a value of decimal digit, i.e. c-'a', would be a lot more useful, because it would let you get rid of your c-87 in multiple spots.
char array[SIZE];
long factor=1;
long result=0;
for(int i=0; i<SIZE; i++)
{
result+=returnVal(foo[i])-87)*factor;
factor*=100;
}
This should work for as long as long is large enough to hold the value of 100^the position and, of course, as long as the result does not overflow.

Create a table using arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Our profeesser assigned this project but Im at a loss of how to do it. Normally I would figure it out on my own but Ive got a massive English paper due on the same day and I have to finish that also this weekend. The program is due on 11/12/13 but can be turned in by 11/19/13 with a 20% penalty to grade.
Write and test a C++ program to complete the following project:
Generate a table of numbers for use in a math problem.
Ask the user for three numbers:
The first number represents how many values are to be in the table (1
to 25).
The second number represents the first value in the table. (-1000 to
+1000)
The third number represents the increment between successive values
in the table. (1 to 20)
Iterate through the selected values, generating and saving the following derived values from each value in the iteration:
Square
Square Root (only if the value is positive or zero, display “N/A” for
all other values)
Cube
Cube Root (only if the value is positive or zero, display “N/A” for
all other values)
Whether the number is even or odd
Whether the number is prime or not (Prepare a user-defined function
based on the logic in Assignment 5).
Save the results of the calculations in a set of arrays, one array for each calculated value.
After all values are calculated and saved, display the values in a tabular form with one column for each calculated value and a row for each set of values (corresponding to the first value read from the user).
Note that for each negative value in the first column, display “N/A” in the columns for square root and cube root.
Display “Even” or “Odd” for each number’s even/odd status. Display “True” or “False” for the number’s prime-ness.
Repeat this process until the user enters a count of zero for the number of values in the table.
Bonus: Read a series of three-number sets from a data file named triples.txt and create a table of numbers corresponding to each three-number set. Save the resulting tables of numbers to a single text file named numbers.csv in comma-separated-value format.
Heres' what i have so far:
// TABLEation.cpp : builds a table based on user input.
//
using namespace std;
double square, squareroot,cube,cuberoot;
int initialValue,display,increment;
string even,prime;
const int SIZE=25;
int Value[SIZE];
bool isEven( int integer )
{
if ( integer % 2== 0 )
return true;
else
return false;
}
bool isPrime(int testValue) {
int divisor=0, remainder=0;
if (testValue<2) return false;
for(divisor=2; divisor<=sqrt(testValue);divisor++){
if((testValue % divisor)==0) return false;
}
return true;
}
int _tmain()
{
do{
begining:
cout<<"Enter how many values to show (1-25)."<<endl;
cin>>display;
if((display>0) && (display<=25)){
cout<<"Enter an initial Value (-1000 to 1000)."<<endl;
cin>>initialValue;
}
else{
cout<<"ERRROR! INVALID INPUT!TRY AGAIN"<<endl;
goto begining;
}
if ((initialValue>= -1000) && (initialValue<=1000)){
cout<<"Enter a number to increment by (1-20)"<<endl;
cin>>increment;
}
else{
cout<<"ERRROR! INVALID INPUT!TRY AGAIN"<<endl;
goto begining;
}
}
system("pause");
return 0;
}
where should I go from here?
Since there is no question above I am guessing you want someone to either give you the answer, or give you hints towards the right direction. I am going to pretend you are after the latter. The problem is fairly straightforward.
Generate a table of numbers for use in a math problem.
Ask the user for three numbers:
The first number represents how many values are to be in the table (1 to 25).
he second number represents the first value in the table. (-1000 to +1000)
The third number represents the increment between successive values in the table. (1 to 20)
Since below we see that you are to ask these questions in a loop until the first answer is 0 you could build a function "bool get_input(int &num_values, int &start_num, int &increment)" This function will return false if the user puts in a value that is not within the ranges and true otherwise. Now call this function in a while loop where you exit if the num_values is 0.
Iterate through the selected values, generating and saving the following derived values from each value in the iteration:
This is a for loop where i = start_num and at each iteration you increase i+=increment
for each iteration of your for loop you should be calling the following six functions:
Square
int square(int i) which returns the square of the value.
Square Root (only if the value is positive or zero, display “N/A” for all other values)
bool extract_square_root(int i, float &square_root) which returns false if the value is negative, otherwise it puts the square root into the reference variable.
Cube
int cube(int i) which returns the cube of the value.
Cube Root (only if the value is positive or zero, display “N/A” for all other values)
bool extract_cube_root(int i, float &cube_root) -- as above
Whether the number is even or odd
bool even_or_odd(int i) which returns true if the value is even and false otherwise.
Whether the number is prime or not (Prepare a user-defined function based on the logic in Assignment 5)
bool prime(int i) which returns true if the value is prime. (use assignment 5).
Save the results of the calculations in a set of arrays, one array for each calculated value.
for each result store it in an array (square_root_array, cube_root_array, etc.)
After all values are calculated and saved, display the values in a tabular form with one column for each calculated value and a row for each set of values (corresponding to the first value read from the user).
call a function void display_values(float square_root_array[], ...) which iterates through each of your arrays and prints the values according to the rules listed below:
Note that for each negative value in the first column, display “N/A” in the columns for square root and cube root.
Display “Even” or “Odd” for each number’s even/odd status.
Display “True” or “False” for the number’s prime-ness.
The next part is already handled by our while loop.
Repeat this process until the user enters a count of zero for the number of values in the table.
I will leave the Bonus for you to figure out.
Bonus: Read a series of three-number sets from a data file named triples.txt and create a table of numbers corresponding to each three-number set. Save the resulting tables of numbers to a single text file named numbers.csv in comma-separated-value format.
Good luck, and get used to working all nighters if you plan on taking a lot of CS. It's par for the course.
P.S. If you follow these directions and look up how to do each step where you are unsure, you could get this project off of your plate in a couple hours.